简体   繁体   English

在Swift中哪里初始化我的应用程序的基类

[英]Where to initialize the base class of my app in Swift

I have a class named Home which is the parent class of my app. 我有一个名为Home的类,它是我的应用程序的父类。 Now, I want to initialize this class somewhere so that I can access everything inside the class from wherever I want. 现在,我想在某个地方初始化该类,以便可以从任何地方访问该类中的所有内容。 The starting point of the app is RootViewController . 该应用程序的起点是RootViewController Should I initialize the app in the starting point? 我应该在起点上初始化应用程序吗? If yes, how should I do it so that it can be accessed from everywhere in the app? 如果是,我该怎么做,以便可以从应用程序中的任何位置访问它?

As per my comment above, set a property on the AppDelegate class with the type Home, initialize it in application:didFinishLaunchingWithOptions. 根据我上面的评论,在Home类型的AppDelegate类上设置一个属性,并在application:didFinishLaunchingWithOptions中对其进行初始化。 Now you can access this instance of home through the sharedApplication.delegate. 现在,您可以通过sharedApplication.delegate访问此home实例。

In AppDelegate.swift: 在AppDelegate.swift中:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    var myHome: Home?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        // Override point for customization after application launch.

        self.myHome = Home()

        return true
    }

Then access it in some other class: 然后在其他一些类中访问它:

let delegate = UIApplication.sharedApplication().delegate as AppDelegate
var home = delegate.myHome

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM