Search code examples
objective-cmacosnullnsapplicationdefensive-programming

Can [NSApplication sharedApplication] ever return nil?


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?
  • I cannot safely assume that NSApplication.shared in Swift being non optional guarantees a non NULL return in the Objective-C equivalent as per this example.

Therefore would the following if statement serve any purpose or is this redundant? As a C programmer we are taught to be very careful to NULL check memory allocations or other operations that could fail even if failure is diminishingly unlikely. But does this concern apply to [NSApplication sharedApplication]?

#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.


Solution

  • 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