If a retain (reference) count of an object is greater than 1 in a dealloc method right before releasing does this mean there will be a memory leak?
I was debugging my code to find another issue but then ran into this subtle one. One of my object’s retain counts was 3 in the dealloc method. This object is a property with retain and is only called within the class. Now I imagine that the retain count should be 1 for all objects in the dealloc method before releasing right?
Here’s a sample dealloc method in a custom class:
- (void)dealloc {
// Prints: "myObject retaincount: 3"
NSLog(@"myObject retaincount: %d", [myObject retainCount]);
// myObject retain count will be 2 after this call
[myObject release];
[super dealloc];
}
Is this normal?
If
myObjectis passed to some other object (say ‘anObj’) via a method (say ‘method:’) as inanObjcan retainmyObjectif needed. Then it is perfectly reasonable that whendeallocof the object containingmyObjectis called, the retain count ofmyObjectis more than 1.Your code is still OK: the responsibility of the containing object is to
releaseownership when it’s done with it. After[myObject release],myObjectwon’t be dealloc’ed. Instead, it will be dealloc’ed whenanObjreleases it.