为什么向下转换时我不必使用 ItemsTableViewController 的初始值设定项?初始化了吗?

How come when downcasting I don't have to use an initializer of ItemsTableViewController? Is it initialized?

我正在学习一个教程,我注意到在向下转换时我不必使用对象的初始化方法。对象是否初始化?在下面的 AppDelegate 代码库中,我指的是 ItemsTableViewController。我所要做的就是说 "as!" 但不需要像这样使用初始化方法或双括号 "ItemsTableViewController()".

ItemsTableViewController 是否已初始化?如果是,如何初始化?

//
//  AppDelegate.swift
//  HomepwnerThirdTime
//
//  Created by Laurence Wingo on 4/26/18.
//  Copyright © 2018 Laurence Wingo. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        //create an ItemStore when the application launches
        let itemStore = ItemStore()

        //create an ItemsTableViewController
        //set the window property which is of type UIWindow from the UIApplicationDelegate protocol and downcast this property to an initialized ItemsTableViewController by using as!
        let itemsController = window!.rootViewController as! ItemsTableViewController
        //now access the ItemsTableViewController and set its itemStore property since it is unwrapped in the ItemsTableViewController which needs to be set
        itemsController.itemStore = itemStore
        //we just set the itemStore property of the ItemsTableViewController!  Yayy, WHEW!! Now when the ItemsTableViewController is accessed with that unwrapped ItemStore object then it will be set!!! WHHHHEEEEWWWWW!
        return true
    }
}

转换和初始化彼此无关。

转换只是一种告诉编译器的方式:"Trust me, even though you think this object is one type, I know it really is another type"。

初始化当然是创建一个新对象

在您的代码中,已经通过故事板为您创建了视图控制器。您的代码只是访问这个已经创建的视图控制器。转换是告诉编译器 rootViewController 实际上是 ItemsTableViewController 的一个实例,而不是普通的旧 UIViewController.

rootViewController 确定已初始化。如果不是,那么它将是 nil,使用 as! 转换它会导致错误。在这里,通过向下转型,您没有对 VC 对象做任何事情。您只是在告诉 Swift "yes I'm sure this will be a ItemsTableViewController by the time the code is run, so don't worry about it".

那VC是怎么初始化的?

这与 iOS 处理应用程序启动的方式有关。当您点击一个应用程序时,它会打开并创建一个 UIWindow。然后你的故事板中的第一个 VC 被初始化并设置为 UIWindowrootViewController。完成所有这些之后,您的应用程序代理就会被调用。

请注意,当您在 didFinishLaunching 方法中时,只是创建了 VC。 VC 中的 views 未加载。这就是 viewDidLoad 的目的。