gpt4 book ai didi

ios - 我在 Swinject 中做错了什么?

转载 作者:行者123 更新时间:2023-11-29 05:13:21 24 4
gpt4 key购买 nike

每当我运行此代码时,VCModel 的 init() 都会被调用,但 Swinject 不会将 VCModel 实例注入(inject)到我的 ViewController 中。有人可以告诉我我做错了什么吗?我得到的错误是:

Unexpectedly Found nil while unwrapping an optional value in 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
}

View Controller

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)
}

最佳答案

您可以在 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
}

关于ios - 我在 Swinject 中做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59455176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com