AppDelegate 如何成为 UIApplication 的委托?

How does AppDelegate become UIApplication's delegate?

我只是想了解 UIApplication 的总体架构。我对使用委托的理解如下:

protocol MyDelegate {
    func someProtocolMethod()
}

class SomeClass {

    var delegate: MyDelegate!

    init(){
    }

    func someClassMethod(){
        self.delegate.someProtocolMethod() 
    }
}

class ClassConformingToDelegate: NSObject, MyDelegate {

    let someClass: SomeClass

    override init(){
        someClass = SomeClass()
        super.init()
        someClass.delegate = self // self has to be assigned so that SomeClass's delegate property knows what the conforming class is
    }        

    func someProtocolMethod(){}
}

以类似的方式,AppDelegate 通过实现许多协议方法来符合 UIApplicationDelegate

class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }
}

UIApplication 在其 class 中声明委托如下:

unowned(unsafe) var delegate: UIApplicationDelegate?

但是,为了让这个委托知道 AppDelegate.swift 是真正的委托,必须实例化 UIApplication 并将 AppDelegate.swift 分配给实例,类似于示例多于。所以类似下面的事情应该发生在 AppDelegate.swift:

let application = UIApplication()
application.delegate = self

但是,怎么省略了这一步,AppDelegate仍然有效?

这个问题的答案会因您所谈论的 Xcode/Swift/iOS 版本而略有不同,但基本过程是相同的。

如果您在 Xcode 中创建一个使用 UIKit AppDelegate 生命周期的项目,那么您将在 AppDelegate.swift 文件的开头看到 @main 行。

这告诉编译器该文件包含 UIApplicationDelegate 实现。然后,编译器会为您合成一个 main 函数来执行所有必需的设置,包括创建 AppDelegate 的实例并将其分配给 UIApplication 实例。

在 Swift 的早期版本中,您会看到 @UIApplicationMain 基本上做同样的事情。

您可以省略 @main/@UIApplicationMain 并创建您自己的 main 来完成所有必需的工作,但这通常不是必需的。

有了 SwiftUI,您现在可以选择在创建项目时使用 SwiftUI 生命周期而不是 UIKit 生命周期。在这种情况下,您有一个 App 结构。此文件仍包含 @main 并用于启动应用的视图层次结构。