为什么视图控制器创建了两次?

时间:2018-01-25 19:44:36

标签: ios swift viewcontroller

我的AppDelegate::didFinishLaunchingWithOptions内有以下代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    createContainer { container in
        let storyboard = self.window?.rootViewController?.storyboard

        guard let vc = storyboard?.instantiateViewController(withIdentifier: "Main") as? MainViewController else {
            fatalError("Cannot instantiate root view controller")
        }

        vc.context = container.viewContext
        self.window?.rootViewController = vc
    }

    return true
}

我的MainViewController在启动时创建,堆栈显示以下内容:

0 MainViewController.viewDidLoad()
UIApplicationMain
main
start

然后在以下行中创建:

self.window?.rootViewController = vc

这是我第一次看到两次创建的vc 这是正常的吗? 我有办法阻止这个吗?

1 个答案:

答案 0 :(得分:3)

在收到UIApplicationMain消息之前,

application:didFinishLaunchingWithOptions:会自动实例化主故事板的初始视图控制器。您不应该在application:didFinishLaunchingWithOptions:中“手动”实例化它。