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 myObject
is passed to some other object (say 'anObj') via a method (say 'method:') as in
[anObj method:myObject];
anObj
can retain myObject
if needed. Then it is perfectly reasonable that when dealloc
of the object containing myObject
is called, the retain count of myObject
is more than 1.
Your code is still OK: the responsibility of the containing object is to release
ownership when it's done with it. After [myObject release]
, myObject
won't be dealloc'ed. Instead, it will be dealloc'ed when anObj
releases it.