监听属性的改变
在OC中我们可以重写set方法来监听属性的改变;
在Swift中可以通过属性观察者来监听和响应属性值的变化;
通常是监听存储属性和类属性的改变(对于计算属性,我不需要定义属性观察者,因为我们可以在计算属性的setter中直接观察并响应这种值的变化)。
//: Playground - noun: a place where people can play
import UIKit
class Person: NSObject {
var name : String?
}
我们如何监听Person类中name属性值的改变呢?
属性监听器
1.定义
//: Playground - noun: a place where people can play
import UIKit
class Person: NSObject {
// 属性监听器
var name : String? {
// 属性即将改变
willSet {
print("111")
}
// 属性已经改变
didSet {
print("222")
}
}
}
//
let p = Person()
p.name = "jack"
在给name赋值的时候willSet在didSet之前执行
2.临时变量
class Person: NSObject {
// 属性监听器
var name : String? {
// 属性即将改变
willSet {
print(newValue) //打印:Optional("jack")
}
// 属性已经改变
didSet {
print(oldValue) //打印:nil
}
}
}
//
let p = Person()
p.name = "jack"
willSet里有个临时变量newValue
,didSet里有个临时变量oldValue
。