To nil, or not to nil, that is the question

Let’s take a look at the Objective-C Programming Language, chapter of Declared Properties, section of dealloc:

Note: Typically in a dealloc method you should release object instance variables directly (rather than invoking a set accessor and passing nil as the parameter), as illustrated in this example:

- (void)dealloc {  
    [property release];
    [super dealloc];

If you are using the modern runtime and synthesizing the instance variable, however, you cannot access the instance variable directly, so you must invoke the accessor method:

- (void)dealloc {
    [self setProperty:nil];
    [super dealloc];

So the question is, should we nil the ivar in -dealloc?

My answer is yes, and the reason is ivar is going to be veiled, and nil ivar in -dealloc is future proofing your code, forearm for the next big change of Objective-C.

If you look back closely, Apple is trying very hard to obscure the instance variable concept (especially the direct accessing of ivar):

  1. They first introduced declared properties,
  2. then the dot syntax,
  3. and the recent synthesizing ivar (Objective-C non-fragile ABI 2.0).

They all point to a clear and simple picture:

"ivar is the gateway to the memory management hell, we should get rid of it."

Instead of accessing the ivar directly, using declared property would be a better way to avoid kinds of troubles that related to the object ownership and disposal. No matter what kind of messages: assign, retain, copy or release, all send out through a unified interface, the declared property.

I think that’s why we saw this showing up in -dealloc:

[self setProperty:nil];

I could be wrong, you know

But since @jeff_lamarche and @danielpunkass are talking about it, I would love to let you know my thought on this.


My wild guess is now a failed guess, according to Michael Jurewitz from Apple:

@digdog Actually, not being able to access the underlying ivar on synthesized properties is just a bug that is fixed in recent compilers.

And keep in mind, using accessor in -dealloc should be really carefully considered (even to avoid), not because accessors can be overridden (thanks @hatfinch), but also mutators/accessors are KVO compliant. By invoking any of them, the suitable KVO notifications are sent, unexpected result might happen if your codes are complex enough, especially when you doing that in deconstructor…

So I would nil ivar in this way:

- (void)dealloc {  
    [property release], property = nil;

Note: for the comma operator, please read.


  1. iPhone Development: Dealloc
  2. iPhone Development: More on Dealloc
  3. Red Sweater Blog - Don’t Coddle Your Code
  4. Uli’s Web Site: Defensive Coding in Objective-C
  5. The Great Dealloc Debate at Under the Bridge
  1. uniquechandeliers reblogged this from digdog
  2. cocoaheads reblogged this from digdog
  3. digdog posted this