加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift - Property Observers

发布时间:2020-12-14 07:08:56 所属栏目:百科 来源:网络整理
导读:在oc世界里,我们为了给一个类的属性赋值时做一些处理操作,主要通过重写getter和setter方法,但是在swift世界里,是通过属性的willSet和didSet(属性监视器)来达到这个效果的 willSet is called just before the value is stored. didSet is called immediately

在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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读