Can you send retain counts to NSLog to aid learning?

浪尽此生 提交于 2019-12-19 10:25:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!