我的UITableViewController
子类MatchTableViewController
具有以下属性:
class MatchTableViewController: UITableViewController {
// MARK: - Properties
var matches = [Match]()
var dataModel: DataModel
var apiModel: APIModel
我想通过覆盖初始值设定项来初始化dataModel
和apiModel
。
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
// Init the DataModel
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
guard let historyEntity = NSEntityDescription.entity(forEntityName: "History",
in: managedContext)
else {
fatalError("Failed to load the History entry")
}
self.dataModel = DataModel(historyEntity: historyEntity,
managedContext: managedContext)
// Init the APImodel
self.apiModel = APIModel()
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Error here
}
override init(style: UITableView.Style) {
// Init the DataModel
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
guard let historyEntity = NSEntityDescription.entity(forEntityName: "History",
in: managedContext)
else {
fatalError("Failed to load the History entry")
}
self.dataModel = DataModel(historyEntity: historyEntity,
managedContext: managedContext)
// Init the APImodel
self.apiModel = APIModel()
super.init(style: style)
// Error here
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
Xcode在两次'super.init' isn't called on all paths before returning from initializer
调用之后立即给我错误super.init
。我不确定我在这里缺少什么。
答案 0 :(得分:3)
问题是,如果未分配内部guard
的值,则不会调用super.init(...)
,也不会分配非可选变量。但是您想将fatalError
扔到else {...}
中,所以在这里调用super.init(...)
毫无意义。
因此,请先致电super.init(...)
,然后再做其他事情
override init(...) {
super.init(...)
... // do other stuff
}
然后确保在调用super.init(...)
之前分配所有非可选的全局变量。如果不同(例如您的情况),请将这些变量设为可选
var variable: Type?
答案 1 :(得分:0)
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
当重写所需的init方法时,'UITableViewCell'的子类必须提供初始化程序'init(coder:)'
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}