Search code examples
swiftcocoacocoa-touchuikitxcode12

What does "@main" mean in Xcode 12?


Xcode 12 includes support for using @main in place of @UIApplicationMain or @NSApplicationMain in UIKit- or AppKit-based apps. source

Newly created Xcode 12 project now using @main to indicate the application starting point.

  1. What does it mean?
  2. What does it do?
  3. How the app start now?

Read a few blog posts that say that @main replaces @UIApplicationMain and in order to make it work a static main method needs to be defined. However, there is no main method in the AppDelegate, and the app launches with no issues.

macOS project created in Xcode 12

import Cocoa

@main
class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(_ aNotification: Notification) {}

    func applicationWillTerminate(_ aNotification: Notification) {}
}

iOS project created in Xcode 12

import UIKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { return true }

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {}
}

Solution

  • UIApplicationMain first instantiates UIApplication and retains its instance to serve as the shared application instance (UIApplication.shared) and then instantiates the app delegate marked @Main as the application instance's delegate. The main method exists as a type method.