我只是想了解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
在其类中声明委托如下:
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
,用于启动应用程序的视图层次结构。