我在 Swinject 中做错了啥?
Posted
技术标签:
【中文标题】我在 Swinject 中做错了啥?【英文标题】:What am I Doing wrong in Swinject?我在 Swinject 中做错了什么? 【发布时间】:2019-12-23 12:12:55 【问题描述】:每当我运行此代码时,都会调用 VCModel 的 init(),但 Swinject 不会将 VCModel 实例注入到我的 ViewController。有人可以告诉我我做错了什么吗? 我得到的错误是:
在展开可选值时意外发现 nil ViewController viewModel.cellModels
AppDelegate
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
// Override point for customization after application launch.
container = Container() con in
con.register(VCModeling.self) _ in
VCModel()
con.storyboardInitCompleted(ViewController.self) r, c in
c.viewModel = r.resolve(VCModeling.self)!
let window = UIWindow(frame: UIScreen.main.bounds)
window.backgroundColor = UIColor.white
window.makeKeyAndVisible()
self.window = window
let bundle = Bundle(for: ViewController.self)
let storyboard = SwinjectStoryboard.create(name: "Main", bundle: bundle, container: container)
window.rootViewController = storyboard.instantiateInitialViewController()
return true
视图控制器
private let disposeBag = DisposeBag()
var viewModel: VCModeling!
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view.
viewModel.cellModels
.bind(to: tableView.rx.items(cellIdentifier: "myCell", cellType: MyCellClass.self))
i, cellModel, cell in
cell.viewModel = cellModel
.disposed(by: disposeBag)
【问题讨论】:
【参考方案1】:你能在 AppDelegate.swift 中试试下面的代码吗
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
// Override point for customization after application launch.
container = Container() con in
con.register(VCModeling.self) _ in
VCModel()
con.storyboardInitCompleted(ViewController.self) r, c in
c.viewModel = r.resolve(VCModeling.self)!
let window = UIWindow(frame: UIScreen.main.bounds)
window.backgroundColor = UIColor.white
window.makeKeyAndVisible()
self.window = window
window.rootViewController = c
return true
【讨论】:
你从哪里得到模型?在 AppDelegate 中 这不是 Swinject 必须要做的吗?【参考方案2】:AppDelegate
中的代码 → application:didFinishLaunchingWithOptions
方法似乎可以正常工作。我已经用以下代码验证了它:
class ViewController: UIViewController
var viewModel: VCModeling!
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view.
print(viewModel.uuid)
protocol VCModeling
var uuid: UUID get
class VCModel: VCModeling
let uuid: UUID
init()
self.uuid = UUID()
我不知道你的VCModel
的init
方法是什么样的,但是看着
...
// Do any additional setup after loading the view.
viewModel.cellModels
...
从您得到的错误中:
Unexpectedly Found nil while unwrapping an optional value in ViewController viewModel.cellModels
它看起来像cellModels
,我认为它是隐式解包属性,你必须初始化它VCModel
的init
方法。
【讨论】:
以上是关于我在 Swinject 中做错了啥?的主要内容,如果未能解决你的问题,请参考以下文章