Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you need to call willChangeValueForKey: and didChangeValueForKey:?

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?

like image 855
Sophistifunk Avatar asked Jul 16 '10 00:07

Sophistifunk


1 Answers

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.

like image 68
Yuji Avatar answered Oct 21 '22 15:10

Yuji