gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 09:30:45 27 4
gpt4 key购买 nike

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

在我指定的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com