微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

AppDelegate如何成为UIApplication的委托?

如何解决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仍然有效?

解决方法

根据您所讨论的Xcode / Swift / iOS版本,此问题的答案略有不同,但是基本过程相同。

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

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

在早期版本的Swift中,您会看到@UIApplicationMain基本上起到了相同的作用。

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。