when to use “willChangeValueForKey” and “didChangeValueForKey”?

前端 未结 8 808
我在风中等你
我在风中等你 2021-01-30 10:53

I saw these lines in a demo project, but I couldn\'t understand why it did that.

[self willChangeValueForKey:@\"names\"];
[self didChangeValueForKey:@\"names\"];         


        
相关标签:
8条回答
  • 2021-01-30 11:47

    Agree with Barry. I just meet the same problem. Here is a case of using those two methods. I declared a readonly property. So I can't use the property's accessor to change the value.

    @property (nonatomic, readonly) BOOL var;
    

    When I want to change the "var", I need to call these two methods manually. Otherwise, observers won't get notified.

    self willChangeValueForKey:@"var"];
    var = YES;
    [self didChangeValueForKey:@"var"];
    
    0 讨论(0)
  • 2021-01-30 11:55

    Posting this in July 2013, and it no longer seems to be necessary to call will/didChangeValueForKey. It seems to be taken care of automatically, even if you have a custom setter.

    0 讨论(0)
提交回复
热议问题