我在 Swinject 做错了什么?



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

在 中解开可选值时意外发现 nil 视图控制器视图模型.单元格模型

应用委托

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

你能在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
}

AppDelegateapplication: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()
}
}

我说不出你VCModelinit的方法是什么样子的,但看着

...
// Do any additional setup after loading the view.
viewModel.cellModels
...

从您收到的错误中:Unexpectedly Found nil while unwrapping an optional value in ViewController viewModel.cellModels

看起来cellModels我假设它是隐式解包的属性,您必须VCModelinit方法对其进行初始化。

相关内容

  • 没有找到相关文章

最新更新