-dealloc
Jeff LaMarche and Daniel Jalkut discuss whether to set Objective-C ivars to nil
in your -dealloc
methods. LaMarche responds. Assuming reasonable quality code, I’m not sure that it makes a huge difference either way, though I tend to lean towards Jalkut’s “don’t mask symptoms” camp. Jeff Johnson makes an interesting point in a comment:
As Mac developers who distribute via the internet, we can get a crash report (from a user, not from Apple, grr!), find the bug, fix the crash, and release a software update all within an hour. Thus, we tend to favor not ‘coddling’ our code, as Daniel puts it. iOS developers, on the other hand, are hostages to the app store approval process. Of course, if your iOS app is crashing in production, one wonders how it got through the approval process in the first place or what the point is of the process, but in any case, your coding precautions may be different for that case.
This sounds like an argument for using macros so that you can easily change your decision based on how you are testing or deploying the code.
1 Comment RSS · Twitter
I like the idea of failing fast. But leaving an ivar as a dangling pointer isn't failing fast, unless you have NSZombieEnabled on. I've seen dangling ivars get re-allocated as another object. Or sometimes somebody else has a reference to the object, so it isn't reaped. In either case, strange things happen when you message it, but there isn't always a crash.
Setting to a known-bad bit pattern like 0xF…F would at least SEGFAULT reliably.
But I don't like doing that — deliberately putting an object in an invalid state bothers me. Maybe that's an impractical, OCD/academic personal issue, but I have strong feelings about it.
For what it's worth, I use synthesized properties for everything, unless I have a reason not to. So my -dealloc looks like "self.somIvar = nil;". I treat explicit retain/release calls as a code smell. I've read rationals (subclassing, KVO, etc.) for why using properties in a dealloc is a bad idea, and while they do make sense, my experience has been that they simplify the common case so much that they're worth using. (At least for iOS apps, where memory is scarce & manually-managed, apps tend to be smaller, and there aren't any bindings.)