NSMutableArray内存管理 [英] NSMutableArray memory management

查看:197
本文介绍了NSMutableArray内存管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  NSMutableArray * a1 = [[NSMutableArray alloc] init]; 
NSMutableArray * a2 = [NSMutableArray array];

TempObj * obj = [[TempObj alloc] init]; //假设为每个obj重复这一行
[a1 addObject:obj];
[a1 addObject:obj2];
[a1 addObject:obj3];
[a1 addObject:obj4];

[obj release];
[obj2 release];
[obj3 release];
[obj4 release];

[a1 release];

Ok所以a2是一个autorelease obj,所以我不必调用release?还有你怎么知道什么时候你得到一个自动释放对象?



对于a1,我不必循环通过数组和释放每个对象第一?如果我调用[a1 removeAllObjects]; [b]

我应该在ive将这些对象添加到数组之后释放这些对象吗?

$ b $当你添加一个对象到数组时,它会调用 retain 。如果你不释放你的指针到那个对象,它将是一个泄漏。当你释放数组时,它会调用 release 上所有的对象,因为它以前调用 retain



对于autorelease vs release,除了可能读取文档外,唯一的方法是通过方法的名称。我相信规则一般是,如果你没有分配对象,那么你不负责释放它。



关于对象创建方法,所有方便的方法( array: arrayWithObjects: arrayWithArray:等)返回自动释放对象。然而,它们相应的init方法( init: initWithObjects: initWithArray:等)不会 - 如果你调用它们,你负责在返回的对象上调用 release



我似乎回想起这个话题上的一些其他问题 - 你可以尝试搜索一个更彻底的解释。


NSMutableArray *a1 = [[NSMutableArray alloc] init];
NSMutableArray *a2 = [NSMutableArray array];

TempObj *obj = [[TempObj alloc] init]; //assume this line is repeated for each obj
[a1 addObject:obj];
[a1 addObject:obj2];
[a1 addObject:obj3];
[a1 addObject:obj4];

[obj release];
[obj2 release];
[obj3 release];
[obj4 release];

[a1 release];

Ok so a2 is an autorelease obj so i dont have to call release on it? Also how do you know when you get an autorelease object?

And for a1, i dont have to loop through the array and release each object first? What if i called [a1 removeAllObjects]; does that call [[a1 objectAtIndex:#] release];

Am i supposed to release those objects after ive added them to the array?

解决方案

When you add an object to an array, it calls retain on that object. If you don't release your pointer to that object, it will be a leak. When you release the array, it will call release on all of the objects that it holds, since it called retain previously.

As for autorelease vs release, the only way to know for sure (aside from possibly reading the documentation) is by the name of the method. I believe the rule in general is that if you didn't allocate the object, then you aren't responsible for releasing it.

Regarding the object creation methods, all of the convenience methods (array:, arrayWithObjects:, arrayWithArray:, etc.) return autoreleased objects. However, their corresponding init methods (init:, initWithObjects:, initWithArray:, etc.) do not - if you call them, you are responsible for calling release on the returned object.

I seem to recall a few other questions on this topic here - you might try searching around for a more thorough explanation.

这篇关于NSMutableArray内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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