为什么在向下转换时我不必使用ItemsTableViewController的初始化程序?它被初始化了吗?

时间:2018-04-29 15:22:24

标签: ios swift downcast

我正在完成一个教程,我注意到在向下转换时我没有必要使用该对象的初始化方法。对象是否已初始化?在下面的AppDelegate代码库中,我指的是ItemsTableViewController。我所要做的只是说" as!"但是并不需要像这样使用init方法或双括号" 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
    }
}

2 个答案:

答案 0 :(得分:1)

投射和初始化彼此无关。

强制转换只是告诉编译器的一种方式:"相信我,即使你认为这个对象是一种类型,我知道它确实是另一种类型"。

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

在您的代码中,您的视图控制器已经通过故事板为您创建。您的代码只是访问这个已创建的视图控制器。演员表示你告诉编译器rootViewController实际上是ItemsTableViewController的实例,而不是普通的UIViewController

答案 1 :(得分:1)

#Loop through every row in DF1 and calculate all the distances to instutions a, b, c. Append to DF1 smallest distance + DF2$ID. #This only gives me the pairwise distance for (i in nrow(DF1)){ result <- distanceCALC(DF1[i,c('longitude', 'latitude')], DF2_vec) } #Somehow take shortest distance for each row*column distance matrix shrtdist <- rbind(shrtdist, min(result[,], na.rm = T)) 肯定是初始化的。如果不是那么它将是rootViewController,并且使用nil投射它会导致错误。在这里,通过向下转换,您没有对VC对象做任何事情。你只是告诉Swift&#34;是的,我确定在代码运行时这将是as!,所以不要担心它#34;。

VC如何初始化?

这与iOS如何处理应用程序的启动有关。当您点按某个应用时,它会打开并创建ItemsTableViewController。然后初始化故事板中的第一个VC并将其设置为UIWindow的{​​{1}}。完成所有这些后,将调用您的app委托。

请注意,当您使用rootViewController方法时,只是创建了VC。未加载VC中的视图。这是UIWindow的用途。