swift中的didSet和willSet使用过程中需要注意的地方:
将下面的这段代码放在Xcode的Storyboard中,观察name和nickName中print的数据
import UIKit
class Manager {
private var _nickName: String = ""
var name: String? = nil { //这里有没有 “= nil” 都是一样的效果
didSet {
print(name)
}
}
var nickName: String {
set {
_nickName = newValue
print(newValue)
}
get {
return _nickName
}
}
init(name: String, nickName: String) {
self.name = name
self.nickName = nickName
updateName("function setting name")
updateNickName("function setting nickname")
}
func updateName(name: String) {
self.name = name
}
func updateNickName(nickName: String) {
self.nickName = nickName
}
}
let manager = Manager(name: "init setting name", nickName: "init setting nickname")
manager.name = "instance setting name"
manager.nickName = "instance setting nickname"
NOTE
The willSet and didSet observers of superclass properties are called when a property is set in a subclass initializer, after the superclass initializer has been called. They are not called while a class is setting its own properties, before the superclass initializer has been called.