我是一个自学成才的iOS编程新手,并且已经完成了一本入门教材。我正试图发布我的第一个移动应用程序,所以我要回去清理我的代码。我使用的教科书强调了“依赖注入”,但我一直在努力使它们的简单示例适应更复杂的应用程序。
应用程序作为shell运行,检索/分析要填充的txt文件。我成功地连接了检索/分析数据的模型和需要使用以下代码填充的TableViewController:

MyTableViewController {
    var data: Data!
}

AppDelegate {
    var window: UIWindow?
    let data = Data()

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

        let navCon = window!.rootViewController as! MyNavigationController
        let tableVC = navCon.topViewController as! MyTableViewController
        tableVC.data = data

        return true
}

然后我将导航控制器嵌入TabBarController中,因为应用程序将有其他选项卡。我尝试了同样的过程设置rootViewController,然后向下钻取,直到我可以设置我的数据变量,但我找不到正确的方法分层viewcontroller并不断得到错误;
'致命错误:在展开可选值时意外找到nil'
我尝试了两种不同的方法:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        let tabBarCon = window!.rootViewController as! MyTabBarController
        let navCon = tabBarCon.presentedViewController as! MyNavigationController
        let tableVC = navCon.topViewController as! MyTableViewController
        tableVC.data = data

        return true
}


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

        let tabBarCon = window!.rootViewController as! MyTabBarController
        let navCon = MyNavigationController()
        tabBarCon.viewControllers = [navCon]

        let tableVC = navCon.topViewController as! MyTableViewController
        tableVC.data = data

        return true
}

有没有解决方法来纠正这个错误,或者我在这个过程中出错了?同样,我有一个文件,它会拉入一个txt文件,然后创建一个字典。我需要一个单独的TableViewController来访问字典来填充自己,但我希望以最有效和苹果公司提倡的方式实现这一点,而不是像我在第一个设计中那样全部放在同一个文件中。
谢谢你的帮助!

最佳答案

对于依赖注入,我建议您使用Typhoon。根据我的经验,这是最好的工具之一。这将帮助您实现如下应用程序组合:

/*
 * This is the definition for our AppDelegate. Typhoon will inject the specified properties
 * at application startup.
 */
public dynamic func appDelegate() -> AnyObject {
    return TyphoonDefinition.withClass(AppDelegate.self) {
        (definition) in

        definition.injectProperty("cityDao", with: self.coreComponents.cityDao())
        definition.injectProperty("rootViewController", with: self.rootViewController())
    }
}

10-07 12:47