Search code examples
swiftmacoscocoansapplicationnsapplication-delegate

Does an NSApplication require an NSApplicationDelegate?


I noticed that the documentation for NSWindowDelegate reads (emphasis mine):

A set of optional methods that a window’s delegate can implement to respond to events, such as window resizing, moving, exposing, and minimizing.

However the documentation for NSApplicationDelegate reads:

A set of methods that manage your app’s life cycle and its interaction with common system services.

This does not have the word optional. I find that not including the delegate reduces the executable size of the application and that if I will only be using a single window for the entire lifetime of the application seem to be able to replace this:

public func applicationShouldTerminateAfterLastWindowClosed(_ _: NSApplication) -> Bool {
    return true
}

With a the following method in the NSWindowDelegate:

public func windowWillClose(_ _: Notification) {
    NSApp.stop(nil)
}

The behavior appears the same however I could find no indication anywhere that not having an NSApplicationDelegate is officially supported by Apple. Are there any unforeseen consequences to this?


Solution

  • While this doesn't appear to be explicitly documented, given the fact that

    1. NSApplication.delegate is declared nullable (@property (nullable, weak) id<NSApplicationDelegate> delegate¹), so NSApplication is capable of having no delegate,
    2. All NSApplicationDelegate methods are marked as @optional², so delegate objects are not required to respond to any protocol methods, and
    3. It's entirely possible to set up and run an app by calling NSApplicationMain(argc, argv) from a bare Obj-C main.m with no other code/setup whatsoever

    it's pretty safe to say that you don't strictly need an app delegate to write an AppKit app — you just won't be informed of app lifecycle events this way. The app delegate infrastructure, as it stands, exists to inform you of various events, but doesn't strictly depend on your responding to them.


    [1][2] NSApplication.h, shipped with the macOS SDK, is not publicly available online, so I don't have a resource I can link to directly for this. If you're writing a macOS app, you can see the contents of this file by ⌘-Clicking a symbol found in this file, like NSApplication, NSApplicationDelegate, NSApplicationMain, etc.; or on disk at the macOS SDK path > System/Library/Frameworks/AppKit/Versions/Current/Headers/NSApplication.h