Hacker News new | ask | show | jobs
by pashields 5372 days ago
Can you expand on this, as the resistance to this style has always confused me. The concern you are presenting is that a subclass could implement the setFoo method, and do so in a way that: 1) does not call [super setFoo:], and 2) does not follow the convention of handling memory management appropriately?

My problem with this argument is that the user could botch release just as well. Maybe they are slightly more likely to botch the setter, but either way they are botching it.

1 comments

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.

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!