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];
}
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):
They all point to a clear and simple picture:
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];
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.
loading…