问题
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-
回答1:
Not only is it possible, it's very easy too:
NSLog(@"retain count=%d",[obj retainCount]);
回答2:
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
回答3:
In the debugger console, you could type: print (unsigned int)[thing retainCount]
来源:https://stackoverflow.com/questions/1407517/can-you-send-retain-counts-to-nslog-to-aid-learning