I copied this example from this topic. It’s better to release the ivar directly.
It’s better to release the ivar directly. If a subclass overrides the
setter methods of a property, your object might leak because your
setter is not called.
@interface ClassA
@property (readwrite, retain) id anObject;
@end
@interface ClassB : ClassA
@end
@implementation ClassA
@synthesize anObject;
- (void)dealloc {
self.anObject = nil;
[super dealloc];
}
@end
@implementation ClassB
- (void)setAnObject: (id)anObject {
// do nothing!
}
@end
I don’t see any difference between [anObject release] and self.anObject = nil.
Because
self.anObject = nil
is equal to
[anObject release];
anObject=nil;
Why I don’t have memory leak with [anObject release] ?
This is incorrect, and is the source of your confusion.
self.anObject = nildoes NOT translate into a direct ivar access. It instead becomesAnd since you’ve overridden the
-setAnObject:method to do nothing, the underlying instance variable is never getting released, and you are thus leaking memory.Incidentally, this is exactly why you should avoid using setter methods inside your
initanddeallocmethods. Subclasses can override them to do unconventional things.