在iphone中保留计数 [英] retain count in iphone

查看:115
本文介绍了在iphone中保留计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 [anArray retainCount] 来获取数组的保留计数..(我知道不应该使用这个,但我只是用于学习保留概念)

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)

以下是我的代码。

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....

推荐答案

请自己帮一个忙>不查看 retainCount 尝试了解内存管理规则的工作原理。请参阅友好的Apple 内存管理指南

Please do yourself a favor and don't look at retainCount trying to learn how the memory management rules work. Instead refer to the friendly Apple Memory Management Guide.

在你的例子中:

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

您已经分配了anArray(通过调用 alloc ),所以你负责调用 release

You have allocated "anArray" (by calling alloc), so you are responsible for calling release.

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

现在,您已经获得了一个新对象(泄漏原始对象,如seand所说)。这次,您不拥有该对象(因为 componentsSeparatedByString 没有 alloc 副本在其名称中),所以你不能释放它。

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.

不要担心retainCount是什么;倾向于你自己编织和释放你应该和不释放你不拥有的物体的物体。

Don't worry about what the retainCount is; tend to your own knitting and release objects that you should and don't release objects you don't own.

这篇关于在iphone中保留计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆