Phase 1
1. A designated or convenience initializer is called on a class.
2. Memory for a new instance of that class is allocated. The
memory is not yet initialized.
3. A designated initializer for that class confirms that all stored
properties introduced by that class have a value. The memory for
these stored properties is now initialized.
4. The designated initializer hands off to a superclass initializer to
perform the same task for its own stored properties.
5. This continues up the class inheritance chain until the top of
the chain is reached.
6. Once the top of the chain is reached, and the final class in the
chain has ensured that all of its stored properties have a value,
the instance’s memory is considered to be fully initialized, and
phase 1 is complete.
Phase 2
1. 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.
2. Finally, any convenience initializers in the chain have the option
to customize the instance and to work with self.
上面总结:
第一阶段指, 初始化从上到下初始化完成, 从上到下指父类
第二阶段指, 初始化链结束后, 可以对继承的属性进行修改, 对方法进行调用
Tips
- 初始化方法中给属性赋值, 不会走
willSet
和didSet
, 但在初始化方法中调用的其他方法, 其他方法给属性赋值会走上面的两个方法
class A {
init() {
}
convenience init(k: Int) {
self.init()
}
}
class AA: A {
var a = 10 {
didSet {
print("\(a)")
}
}
override init() {
self.a = 10
super.init()
self.a = 20
self.run()
self.a = 40
}
convenience init(a: Int) {
self.init()
self.a = 50
}
func run() {
self.a = 30
}
}
let a = AA(a: 1)
//print
30
- 便利构造器, 在使用
self
之前, 必须调用自己的指定构造器. - 指定构造器, 在访问方法或者父类的属性之前, 必须调用父类的指定构造器
- 调用父类构造器之前, 必须给自己的没赋值的确定属性(指不是可选, 没有使用
?!
) 赋值. - 如果子类的属性都有默认值, 或者是可选的, 即使子类会自动继承父类的构造器, 但如果子类有其他的指定构造器, 这个就失效了.
class C {
var a: Int
init(a: Int) {
self.a = a
}
}
class CC: C {
var b = 10
}
let c = CC(a: 10)
print(c.a)
// print
10
- 失败的初始化
class D {
init?() {
return nil
}
}
let d = D()
print(d)
// print
nil
网友评论