swift - Property Observers

在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

发布了67 篇原创文章 · 获赞 12 · 访问量 15万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章