在将对象添加到集合之前使用自动释放? [英] Use autorelease before adding objects to a collection?

查看:135
本文介绍了在将对象添加到集合之前使用自动释放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在查看StackOverflow上提出的问题,但在Objective-C中有很多关于内存管理的内容,我找不到我想要的答案。

I have been looking through the questions asked on StackOverflow, but there are so many about memory management in Objective-C that I couldn't find the answer I was looking for.

问题是,在将新创建的对象添加到集合(如NSMutableArray)之前,是否可以(并建议)调用autorelease?或者我应该在添加后明确地发布它。 (我知道NSMutableArray会保留对象)

The question is if it is ok (and recommnded) to call autorelease before adding a newly created object to a collection (like NSMutableArray)? Or should I release it explicitly after adding it. (I know NSMutableArray willl retain the object)

这说明了我的问题:

场景A(自动释放):

Scenario A (autorelease):

- (void) add {
   // array is an instance of NSMutableArray

   MyClass *obj = [[[MyClass alloc] init] autorelease];

   [array addObject:obj];
}

场景B(显式版本):

Scenario B (explicit release):

- (void) add {
   // array is an instance of NSMutableArray

   MyClass *obj = [[MyClass alloc] init];

   [array addObject:obj];

   [obj release];
}

我认为两者都是正确的,但我不确定,我肯定不会我不知道最喜欢的方式是什么。

I assume both are correct, but I am not sure, and I sure don't know what the preffered way is.

Objective-C大师可以对此有所了解吗?

Can the Objective-C gurus shed some light on this?

推荐答案

两者都是正确的,并且会像你期望的那样工作。

Both are correct and will work as you're expecting them to.

我个人更喜欢使用后一种方法,但是只是因为我喜欢明确何时释放对象。通过自动释放对象,我们所做的只是说这个对象将在未来的某个任意点发布。这意味着您可以将自动释放的对象放入数组中,销毁数组,并且对象可能(可能)仍然存在。

I personally prefer to use the latter method, but only because I like to be explicit about when objects get released. By autoreleasing the object, all we're doing is saying "this object will get released at some arbitrary point in the future." That means you can put the autoreleased object into the array, destroy the array, and the object might (probably) still exist.

使用后一种方法,对象将获得用阵列立即销毁(假设没有其他任何东西出现并在此期间保留它)。如果我在一个内存受限的环境(比如iPhone)中我需要注意我正在使用多少内存,我将使用后一种方法,因此我没有那么多的对象挥之不去一个NSAutoreleasePool。如果内存使用对你来说不是一个大问题(通常也不适合我),那么任何一种方法都是完全可以接受的。

With the latter method, the object would get destroyed immediately with the array (providing that nothing else has come along and retained it in the meantime). If I'm in a memory-constrained environment (say, the iPhone) where I need to be careful about how much memory I'm using, I'll use the latter method just so I don't have so many objects lingering in an NSAutoreleasePool somewhere. If memory usage isn't a big concern for you (and it usually isn't for me, either), then either method is totally acceptable.

这篇关于在将对象添加到集合之前使用自动释放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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