问题描述
我只是想了解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生命周期的项目,那么您将在@main
文件的开头看到行AppDelegate.swift
。
这告诉编译器此文件包含UIApplicationDelegate
实现。然后,编译器会为您综合一个main
函数,该函数执行所有必需的设置,包括创建AppDelegate
的实例并将其分配给UIApplication
实例。
在早期版本的Swift中,您会看到@UIApplicationMain
基本上起到了相同的作用。
您可以省略@main
/ @UIApplicationMain
并创建自己的主管来完成所有必需的工作,但这通常不是必需的。
使用SwiftUI,您现在可以在创建项目时选择使用SwiftUI生命周期而不是UIKit生命周期。在这种情况下,您有一个App
结构。该文件仍包含@main
,用于启动应用程序的视图层次结构。