View Controller中的依赖注入 [英] Dependency Injection in View Controller

查看:180
本文介绍了View Controller中的依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用依赖注入而不是跟随单例.这就是我想要达到的目的.当我运行应用程序时,在"No "decodeObject" candidates produce the expected contextual result type "ModelManager"上出现错误.知道如何以正确的方式实现依赖注入吗?

I am trying to use dependency injection instead of following singletons. This is how I am trying to achieve. When I run the application I am having an error on "No "decodeObject" candidates produce the expected contextual result type "ModelManager" on that. Any idea how can I implement dependency injection in a right way?

我的模型课:

class ModelManager {
var results: MyCustomClass

init(results: MyCustomClass) {
    self.results = results
}
func update(customDataInfo: MyCustomClass!) {
    self.results = customDataInfo
}
}

MyViewController.swift

MyViewController.swift

class MyViewController: UIViewController {

private let modelManager: ModelManager

init(modelManager: ModelManager) {
    self.modelManager = modelManager
    super.init(nibName: nil, bundle: nil)
    self.modelManager.modelManagerUpdate = self as ModelManagerUpdate
}

 required init?(coder aDecoder: NSCoder) {
    self. modelManager = aDecoder.decodeObject(value(forKey: "modelManager") as ModelManager)
    super.init(coder: aDecoder)

    fatalError("init(coder:) has not been implemented")
}

override func encode(with aCoder: NSCoder) {
    super.encode(with: aCoder)
    aCoder.encode(self. modelManager, forKey: "modelManager")
}
}

推荐答案

正在使用init?(coder:)初始化程序的事实表明,您的视图控制器是从情节提要中初始化的.在这种情况下,情节提要中不包含ModelManager,因此无法对其进行解码.

The fact that the init?(coder:) initialiser is being used suggests that your view controller is initialised from storyboard. If that is the case, storyboard does not contain ModelManager, thus it cannot decode it.

您可以通过将情节提要初始化包装到您自己的方法中来解决此问题,例如:

You can work around this by wrapping storyboard initialisation into your own method, e.g.:

class MyViewController: UIViewController {
    private var modelManager: ModelManager

    static func create(modelManager: ModelManager) -> MyViewController {
        let vc = /* instantiate vc from storyboard */
        vc.modelManager = modelManager
        return vc
    }
}

如果上述方法不适合您的需求,建议您看看 SwinjectStoryboard 框架.除了基本的DI功能之外,它还提供了将依赖项注入到从情节提要中初始化的视图控制器的功能.

If the above method does not suit your needs, I would suggest you take a look at the SwinjectStoryboard framework. It provides - besides basic DI functionality - ability to inject dependencies to the view controllers initialised from storyboard.

这篇关于View Controller中的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆