Hacker News new | ask | show | jobs
by alextgordon 5374 days ago
If you have an observer listening for changes on the "photographer" key, then `self.photographer = nil;` will send off a KVO event. [photographer release]; will not.

Since your object is likely to be dealloced at an odd time (for instance when an autorelease pool is drained), and in an inconsistent state (half its fields missing), it's much better to do a release.

1 comments

Is there any situation where you would legitimately still have an observer for an object which is being deallocated?
I can contrive one. Class A holds a strong (i.e., retain) reference to an instance of class B in a property "myB". A also has a property "myC" which B observes.

  - (void)dealloc {
    self.someOtherVariable = nil;
    self.myC = nil; // Sends KVO on myC. B sees half-deconstructed A.
    self.myB = nil; // myB now is dealloc'd and stops observing A.
    [super dealloc];
  }
Admittedly this is a real edge case and probably bad design, but it's not overtly terrible. I have a couple cases where objects observe their owners.

BTW thanks for the blog, Mike! I love it.

I'd argue that this would be a bug. B has a weak reference to A here (whether explicitly or just implicitly through KVO) and that weak reference should be cleared out first thing before tearing down the rest of the object. The method should start with a [myB setA: nil], then go on with the rest. Setting that to nil would then remove the observation, solving the problem.

There may well be similar setups which aren't broken which still exhibit the problem, though.

Glad you enjoy the blog!