Home > database >  Should I check [NSApplication sharedApplication] for a nil return?
Should I check [NSApplication sharedApplication] for a nil return?

Time:10-26

In a MacOS app in Objective-C is it possible for [NSApplication sharedApplication] to return nil or is it a safe assumption that this will never return nil?

The Documentation describes the behavior:

Returns the application instance, creating it if it doesn’t exist yet.

However:

  • Is there any possibility to fail to create it? For example if the memory for the NSApplication object cannot be allocated?
  • If such an unexpected error prevents the object from being created would the framework automatically detect this and crash instead of returning nil?
  • Would the following if statement serve any purpose?
#import <Cocoa/Cocoa.h>
int main() {
    if (![NSApplication sharedApplication]) {
        return -1;
    }
    // ...
    [NSApp run];
}

My goal is to write absolutely correct code, not just good enough in almost all cases, while remaining as concise as possible.

CodePudding user response:

sharedApplication is of _Nonnull as the code says and as the documentation seys:

Summary:

Returns the application instance, creating it if it doesn’t exist yet.

Source: sharedApplication

  • Related