views:

60

answers:

3

Hi everyone, if I create an nsmutablestring and then release it , shouldn't the retain count be 0?

my retain count stays 1.

NSMutableString *text = [[NSMutableString alloc]init];

[text release];

NSLog(@"retain count %d ", [text retainCount]);

Am I missing something ?

thanks.

+5  A: 

There's no guarantee that retainCount will return the correct value at any point during the object's lifecycle. If you've created an NSMutableString using [[NSMutableString alloc] init] and you're calling release on it once, you're doing the right thing and shouldn't worry about it.

Nathan de Vries
Thanks . I will run the performance tool instead to see if anything is weird there.
@Nathan de Vries: I was tempted to up vote you for the first sentence but also to downvote you for missing the fact that by the time the NSLog is executed, `text` may well (probably has been) deallocated by the release just above it. The NSLog sends retainCount to an object that technically no longer exists.
JeremyP
Hmm ye u are right about that but i don't seem to get any ACCESS_ERROR which is weird but again I think the object is somehow released later.
It is quite likely already released, but it'd be a complete waste of CPU cycles to clear memory and, thus, `-retainCount` still does the same non-sensical thing it always does.
bbum
+1  A: 

Apple says in its documentation that retainCount is of no use for memory management purposes because the frameworks and autorelease pools can keep hold of an object even if you have released it. http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/occ/intfm/NSObject/retainCount

Robert Redmond
Hmm ok thanks for information. Gonna be very hard for me to debug then.
@user281300: why? Apple provides a number of tools to help you debug memory management issues.
JeremyP
+1  A: 

Since you're doing this for debugging purposes, I'd suggest that you use categories to add some test code to an existing class. Any time you manually retain or release your object, you could call your new methods and use that to track your memory usage.

Tim Rupe
Thanks I will try that as well