在oc世界裏,我們爲了給一個類的屬性賦值時做一些處理操作,主要通過重寫getter和setter方法,但是在swift世界裏,是通過屬性的willSet和didSet(屬性監視器)來達到這個效果的
willSet is called just before the value is stored.
didSet is called immediately after the new value is stored.
var title: String {
willSet {
print( "will set ")
NSThread.sleepForTimeInterval(2)
}
didSet {
print("did set")
self.backgroundColor = UIColor.grayColor()
}
}
我們在屬性title的值即將改變之前 爲了更好理解willSet 和didSet,我們讓線程休眠2s,改變之後,讓view的背景色變爲gray.
在touchesBegan方法裏改變屬性title的值
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
testV.title = "test"
}
果然不出意料, 點擊之後打印will set 然後2s後打印did set 並且bgColor變爲了gary