AppDelegate如何成为UIApplication的委托?

问题描述

我只是想了解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仍然有效?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)