这是一个CocoaChina上面的问题。就是为什么retainCount返回的对象引用值总是跟预期的不一样呢?
这个应该是像我这样初学者一般都会有的疑问,来看下面的一段例子
- NSAlert *alert = [[NSAlert alloc] init];
- [alert setMessageText:@"TEST"];
- [alert setAlertStyle:NSWarningAlertStyle];
- [alert runModal];
- NSLog(@"alert has %lu retainCount",[alert retainCount]);
- [alert release];
结果log里面始终报告retainCount是3。确实很让人费解。(如果你是用别的类做的实验,结果还会更奇怪)经过一番搜索,最后在StackOverFlow找到了解释合理的答案:
Typically there should be no reason to explicitly ask an object what its retain count is (see retainCount). The result is often misleading, as you may be unaware of what framework objects have retained an object in which you are interested. In debugging memory management issues, you should be concerned only with ensuring that your code adheres to the ownership rules.
原文:http://stackoverflow.com/questions/2640568/objectivec-how-to-get-the-reference-count-of-an-nsobject
翻译:通 常我们没有必要去特地查询一个对象的retain count是多少。查询的结果常常会出乎意料。你不清楚framework里面的其他对象对你感兴趣的这个对象进行了多少retain操作。在debug 内存管理的问题时候,你只要关注保证你的代码符合所有者规则即可。(译者:我觉得应该是谁申请(几次)谁释放(几次)原则)
因此在引用计数的内存管理方式里面,我们可以把alloc, retain, copy, new, mutableCopy看作是+1操作。而通常根据原则,你要负责在适当的时候执行-1操作以保证没有内存泄漏。