Just curious if there is anyway to display an objects retain count using NSLog. I just want to print them out to console to help learn how retain/release is working in some simple code?
cheers -gary-
Just curious if there is anyway to display an objects retain count using NSLog. I just want to print them out to console to help learn how retain/release is working in some simple code?
cheers -gary-
Not only is it possible, it's very easy too:
NSLog(@"retain count=%d",[obj retainCount]);
In the debugger console, you could type: print (unsigned int)[thing retainCount]
Hmm -- I get a long and unchanging number -- something I'm doing wrong?
NSString *A = [[NSString alloc] init];
NSLog(@"%u", [A retainCount]);
[A retain];
NSLog(@"%u", [A retainCount]);
PRINTS: 2147483647 both times
I think you might be hitting an issue with NSString where retain and release messages can be sent to a string constant, but they actually have no effect nor alter the objects retainCount. The code below works, change it to use NSString and retain / release have no effect.
Code:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableString *myString = [[NSMutableString alloc] initWithString:@"AB"];
NSLog(@"RC: %d", [myString retainCount]);
[myString retain];
NSLog(@"RC: %d", [myString retainCount]);
[myString release];
NSLog(@"RC: %d", [myString retainCount]);
[myString release];
[pool drain];
return 0;
}
Output:
Running…
TESTBED[12306:a0f] RC: 1
TESTBED[12306:a0f] RC: 2
TESTBED[12306:a0f] RC: 1
gary