问题描述
现在我有一个ClassA : NSObject
,然后在viewcontroller viewDidLoad
中,查看下面的代码:
Now I have a ClassA : NSObject
, and then in the viewcontroller viewDidLoad
, look at the under code:
- (void)viewDidLoad {
ClassA *a = [[ClassA alloc] init];
NSLog(@"a retainCount = %d", [a retainCount]);
ClassA *b = a;
NSLog(@"a retainCount = %d b retainCount= %d ", [a retainCount],[b retainCount]);
[a release];
NSLog(@"a retainCount = %d b retainCount= %d", [a retainCount],[b retainCount]);
[super viewDidLoad];
}
控制台输出如下:
2012-11-02 14:43:35.437 RetainCountTest[1043:207] a retainCount = 1
2012-11-02 14:43:35.439 RetainCountTest[1043:207] a retainCount = 1 b retainCount= 1
2012-11-02 14:43:35.439 RetainCountTest[1043:207] a retainCount = 1 b retainCount= 1
我不明白我打电话给[a release]
时为什么要使用[a retainCount]== 1
?
I don't understand that when I call [a release]
, why the [a retainCount]== 1
?
推荐答案
您永远不应该注意keepCount的注意.它们充其量是令人困惑的,而误导则是最坏的.只需确保它们正确地遵循保留/释放的内存管理规则,而不必考虑keepCounts.
You should never pay attention to retainCount's. They are at best confusing, and at worst misleading. One should just make sure that they follow memory management rules of retain/release correctly, and forget about retainCounts.
来自文档 ..
建议阅读
看到OP的评论
如果有人读过这篇文章,他/她可能会想,哦,retainCount是天赐之物,我仅使用NSLog语句就可以看到对象的完整分配/保留/释放周期.但这实际上不是那样的.您不能说,您拥有所创建对象的唯一所有权.该对象可以由任何其他框架对象保留.通过释放,您只是放弃了所有权.只有在所有其他对象都删除其引用之后,该对象才会被释放.
If one read this, he/she might think, Oh retainCount is godsent, and I can see the complete alloc/retain/release cycle of an object just using an NSLog statement. But it doesn't actually works that way. You cannot say, you have sole ownership of object you create. That object might be retained by any other framework object. And by releasing you are just relinquishing your ownership. The object will get released only after all other objects remove their reference.
我不知道为什么它仍保留在公共API中.
I don't know why it remains in public API.
这篇关于iOS关于retainCount的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!