简体   繁体   English

在iPhone中保留计数

[英]retain count in iphone

I have used [anArray retainCount] to get the retain count of array..(i know this should not be used but i am using just for learning retain concept) 我已经使用[anArray retainCount]来获取数组的保留计数。(我知道这不应该使用,但是我只是用于学习保留概念)

Following is my code. 以下是我的代码。


NSString *str = [[NSString alloc] initWithFormat:@"a,b,c,d"];
NSArray  *anArray =[[NSArray alloc]init];
NSLog(@"Retain count: %i", [anArray retainCount]);
anArray=[str componentsSeparatedByString:@","];
NSLog(@"Retain count: %i", [anArray retainCount]);  

output 输出

Retain count: 2
Retain count: 1

i think it should be opposite but.... 我认为应该相反,但是...

Please do yourself a favor and don't look at retainCount trying to learn how the memory management rules work. 请帮个忙, 不要着眼于retainCount尝试学习内存管理规则的工作方式。 Instead refer to the friendly Apple Memory Management Guide . 相反,请参阅友好的《 Apple 内存管理指南》

In your examples: 在您的示例中:

 NSArray  *anArray =[[NSArray alloc]init];

You have allocated "anArray" (by calling alloc ), so you are responsible for calling release . 您已经分配了“ anArray”(通过调用alloc ),因此您有责任调用release

anArray=[str componentsSeparatedByString:@","];

Now, you have obtained a new object (leaking the original, as seand said). 现在,您已经获得了一个新对象(如肖恩所说,泄漏了原始对象)。 This time, you do not own the object (because componentsSeparatedByString does not have alloc or copy in its name), so you must not release it. 这次,您不拥有该对象(因为componentsSeparatedByString中没有alloccopy ),因此您不能释放它。

Don't worry about what the retainCount is; 不用担心keepCount是什么。 tend to your own knitting and release objects that you should and don't release objects you don't own. 倾向于自己编织和释放应有的对象,而不释放不拥有的对象。

This line... anArray=[str componentsSeparatedByString:@","]; 这行... anArray = [str componentsSeparatedByString:@“,”];

You squished the original assignment of 'anArray' (thus creating a leak). 您压缩了'anArray'的原始分配(因此造成了泄漏)。 In real life, you'd want to [anArray release] first. 在现实生活中,您首先要[anArray版本]。 That's why the retain count went back to 1. 这就是为什么保留数回到1的原因。

The documentation states that the retain count is unlikely to provide any useful information. 该文档指出,保留计数不太可能提供任何有用的信息。 It is NOT a good way to learn about retain and release concepts. 不是学习保留和释放概念的好方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM