ios - 为什么调用 super.init() 会调用我默认的 init()

标签 ios ios7 swift

所以我有一个带有指定初始化器的类,它为每个存储的属性取值。 我所有存储的属性也有一个默认值,所以我假设这个类有一个默认的初始化。

在我指定的 init 中,我调用 super.init()

问题是,如果我在 init 结束时调用它,它会将所有属性加载为默认值,但如果我在开始时调用它,它会按我预期的那样工作。

书上说:

Safety check 1 A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.

As mentioned above, the memory for an object is only considered fully initialized once the initial state of all of its stored properties is known. In order for this rule to be satisfied, a designated initializer must make sure that all its own properties are initialized before it hands off up the chain.

所以我不确定是情况发生了变化还是我做错了什么?

代码:

class ORQuizViewController: UIViewController {
let imageView: UIImageView = UIImageView(image: nil)
let questionLabel: UILabel = UILabel()
let choicesArray: [BlackWhiteButton] = [BlackWhiteButton]()
let correctAnswer: Int = -1

init(image: UIImage!, question: String, choices: [String], answerIndex: Int) {
    super.init()
    imageView = UIImageView(image:image)
    questionLabel = UILabel()
    questionLabel.text = question
    var tempChoices = [BlackWhiteButton]()
    for choice in choices {
        var choiceLabel = BlackWhiteButton()
        choiceLabel.setTitle(choice, forState: .Normal)
        tempChoices.append(choiceLabel)
    }
    choicesArray = tempChoices
    correctAnswer = answerIndex
}

最佳答案

正确的解决方案是调用 super.init 在您分配最终值之前,正如您所观察到的那样。正如您所说,安全检查 1 要求在委托(delegate)之前初始化子类引入的所有属性 - 这是由您的默认分配处理的。

在初始化过程的第 1 阶段应用安全检查 1。

初始化过程的第 2 阶段随后发生 -

Phase 2

Working back down from the top of the chain, each designated initializer in the chain has the option to customize the instance further. Initializers are now able to access self and can modify its properties, call its instance methods, and so on. Finally, any convenience initializers in the chain have the option to customize the instance and to work with self.

因此您需要在第 2 阶段分配最终值。

文档有点不清楚,但您似乎应该继续使用 Objective C 中的典型约定,即首先调用父类(super class) init。

关于ios - 为什么调用 super.init() 会调用我默认的 init(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25829679/

相关文章:

controls - 我可以在某些 View 上阻止 ios7 中出现的控制中心吗?

ios - Firebase Auth 不起作用,但适用于 friend ,很快

ios - 使用 Swift 在 UICollectionView Cell 上点击手势

ios - Firebase 插入具有 2 个关键属性的数据

ios - 使用分页时,iOS TableView 应包含多少行?

ios - 为什么我们在这里使用 ephemeralSessionConfiguration?

ios - AFNetworking:附加参数作为 PUT 请求的查询字符串

css - iOS7 - 如何识别 Safari 工具栏何时显示在移动设备上

ios7 - 在iOS 7上设置VPN配置配置文件

swift - 需要有关 swift 类型推断的帮助