![](/img/trans.png)
[英]When is "required init?(coder aDecoder: NSCoder)" called on a UIView or UIViewController?
[英]Is it OK to have fatalError in required init?(coder aDecoder: NSCoder) when I don't use Storyboards?
我有一個ViewController
,需要使用ViewModel: NSObject
進行初始化。
我的ViewController
實現是:
class ViewController: UIViewController {
let viewModel: ViewModel
init(withViewModel viewModel: ViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
ViewModel
具有簡單的override init
:
class ViewModel: NSObject {
override init() {
super.init()
// Some other logic
}
}
我明白,我需要在ViewController
實現中required init?(coder aDecoder: NSCoder)
,因為它符合NSCoding
協議。 但我不確定在那里有fatalError
是否安全。
當我將fatalError
更改為super.init(coder: aDecoder)
我收到了
屬性'self.viewModel'未在super.init調用中初始化
我不想讓viewModel
成為可選變量,因為在我的App邏輯中它不能是nil
。
另外,當我改變init?(coder...
required init?(coder aDecoder: NSCoder) {
self.viewModel = ViewModel()
super.init(coder: aDecoder)
}
這也不滿足我,因為viewModel
不是唯一的常量,需要在ViewController
初始化期間實現。
所以,我的問題:
init
方法中有fatalError
是否安全? init?(coder...
方法無論如何都不會運行? fatalError
? 謝謝你的幫助!
由於您不使用故事板,因此可以禁用init,因此您將無法在代碼中使用它:
@available(*, unavailable) required init?(coder aDecoder: NSCoder) {
fatalError("disabled init")
}
如果您希望以后使用模擬數據輕松編寫測試,那么在這里您也可以使用依賴注入進行良好的啟動。
視圖控制器:
class ViewController: UIViewController {
let viewModel = ViewModel()
override func viewDidLoad() {
super.viewDidLoad()
viewModel.runFunction()
}
}
視圖模型:
class ViewModel: NSObject {
var networkingService: NetworkingService?
init(withNetworkingService networkingService: NetworkingService = null) {
self.networkingService = networkingService
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.