查看斯坦福 iOS 9 类(class)中的讲座幻灯片 here ,他正在创建一个带有两个初始化器的新 UIView
(一个是从 Storyboard创建的 UIView
,另一个是在代码中创建的)。以下代码写在该特定幻灯片的底部:
func setup() {....} //This contains the initialization code for the newly created UIView
override init(frame: CGRect) { //Initializer if the UIView was created using code.
super.init(frame: frame)
setup()
}
required init(coder aDecoder: NSCoder) { //Initializer if UIView was created in storyboard
super.init(coder:aDecoder)
setup()
}
规则是您必须先初始化所有自己的属性,然后才能从父类(super class)中获取初始化。那么,为什么在这种情况下他会在初始化自己 setup()
之前调用他的父类(super class) init super.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.
最佳答案
我还没有看到这个例子中的所有其余代码,但规则只是在调用 之前必须初始化您的属性(即它们占用的内存必须设置为某个初始值) super.init()
,并不是说你不能运行额外的设置代码。
您甚至可以通过声明您的属性 lazy var
或使用自动初始化为 >无
。然后,您可以在调用 super.init()
后设置它们。
例如:
class Foo: UIView {
var someSubview: UIView! // initializes automatically to nil
lazy var initialBackgroundColor: UIColor? = {
return self.someSubview.backgroundColor
}()
init() {
super.init(frame: .zero)
setup() // do some other stuff
}
func setup() {
someSubview = UIView()
someSubview.backgroundColor = UIColor.whiteColor()
addSubview(someSubview)
}
}
关于ios - 在其父类(super class)初始化之后初始化 UIView init?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38759412/