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

工具导航Map

JSON相关