Do you need to call willChangeValueForKey: and didChangeValueForKey:?

こ雲淡風輕ζ 提交于 2019-12-04 19:27:40

问题


I thought home-cooked @property setters were supposed to look like this:

-(void) setFoo:(Foo *)newFoo {

  // Safeguards 
  // ...

  [self willChangeValueForKey:@"foo"];
  // Switcheroo
  // ...
  [self didChangeValueForKey:@"foo"];
}

But I see a lot of code in blog posts by people who've been doing Cocoa a lot longer than I have, where it's like this:

-(void) setFoo(Foo *)newFoo {

  // Safeguards 
  // ...

  // Switcheroo
  // ...
}

So my question is, do we need to call the KVO-notification methods? Or is it being done magically when you update the private iVar, if you're using the modern runtime?


回答1:


It's done magically unless you opt-out. read this section of the KVO guide. Note that KVC/KVO existed from time immemorial (i.e. before the introduction of @property) so it doesn't matter whether the setter is @synthesized or not. It's not even related to the old/new runtime dichotomy.

The detail of this magic (isa-swizzling) was detailed in a blog post by Mike Ash. It's magic. Basically, when a key is observed, the runtime automagically replaces the implementation of the setter so that it calls the KVO notification.



来源:https://stackoverflow.com/questions/3261139/do-you-need-to-call-willchangevalueforkey-and-didchangevalueforkey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!