如何为UITableViewController子类正确覆盖init()?

时间:2018-12-24 22:40:07

标签: ios swift xcode swift4 viewcontroller

我的UITableViewController子类MatchTableViewController具有以下属性:

class MatchTableViewController: UITableViewController {
    // MARK: - Properties
    var matches = [Match]()
    var dataModel: DataModel
    var apiModel: APIModel

我想通过覆盖初始值设定项来初始化dataModelapiModel

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。我不确定我在这里缺少什么。

2 个答案:

答案 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")
}