search

Home  >  Q&A  >  body text

objective-c - Objectiv-C KVO 要不要在set方法中手动实现 willchange/didChange?

比如?

- (void)setNow:(NSDate *)aDate {
    [self willChangeValueForKey:@"now"];
    _now = aDate;
    [self didChangeValueForKey:@"now"];
}

还是直接

- (void)setNow:(NSDate *)aDate {
    
    _now = aDate;
    //自动调用 willChange didChange方法?
}

2 如果在category里用runtime增加一个属性时,如果需要使用KVO,需要手动使用这两个方法么?

-(void)setStr:(NSString *)str  
{  //这里需要手动使用 willChange didChange么?
    objc_setAssociatedObject(self, & strKey, str, OBJC_ASSOCIATION_COPY);  
}  
漂亮男人漂亮男人2757 days ago489

reply all(2)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-05-02 09:29:56

    If the old value and the new value are different, you need to send a manual notification. Associated objects cannot synthesize setter methods, and setter methods must be given by the programmer. When we kvo this attribute, the runtime detects that we have implemented the setter and will not override this method, so the notification cannot be issued. So this notification also needs to be sent manually

    reply
    0
  • 怪我咯

    怪我咯2017-05-02 09:29:56

    It needs to be written manually, it will not be called automatically.

    reply
    0
  • Cancelreply