[英]iPhone: using retain vs autorelease
Which one of these is better practice? 哪个是更好的做法?
A) retain and release the object myself later A)稍后自己保留并释放对象
NSMutableArray* array = [[self getArray] retain];
....
[array release];
B) autorelease from the function returning the object B)从返回对象的函数中自动释放
getArray {
NSMutableArray* returnedArray = [[[NSMutableArray alloc] init] autorelease];
.....
return returnedArray;
}
The simplest rule of thumb when it comes to memory management in Objective-C is that you should release anything that you've explicitly allocated (alloc), copied (copy), newed up (new), or retained (retain). 关于Objective-C中的内存管理,最简单的经验法则是,您应释放任何已明确分配(分配),复制(复制),更新(新)或保留(保留)的内容。
The release should be done within the scope of the aforementioned actions. 释放应在上述动作的范围内完成。 If you allocate space for an object that is returned by a method, you should autorelease it before returning it.
如果为方法返回的对象分配空间,则应在释放它之前自动释放它。 So, given the two options you've provided, B is the recommended practice.
因此,考虑到您提供的两个选项,建议您使用B。
If you want to return an object you have to use the second approach. 如果要返回对象,则必须使用第二种方法。 In all cases where possible you should use the retain-release approach because this uses less memory.
在所有可能的情况下,都应使用保留释放方法,因为这会占用较少的内存。
You could read and follow Apples guidelines on memory management and performance . 您可以阅读并遵循Apple关于内存管理和性能的准则。
Personally I think the reasons for choosing one way over the other: 我个人认为选择其中一种方法的原因是:
Using Autorelease pros: 使用自动发行专家:
cons: 缺点:
Using retain/release pros: 使用保留/发布专家:
cons: 缺点:
I think, whichever style you choose comes down to the situation your code is in and choosing the best style based on there pro's and con's. 我认为,无论选择哪种样式,都取决于您的代码所处的情况,并根据优缺点选择最佳样式。 I don't think there is any one answer to this.
我认为对此没有任何答案。
new
, alloc init
, retain
, or copy
(NARC) an object, you have to release it. new
, alloc init
, retain
或copy
(NARC)对象,则必须释放它。 release
the object when he is done with it. release
对象。 retain
on the object. retain
对象。 Some comments: 一些评论:
Example: 例:
// created with autoreleased, just call retain if you intend to keep it
NSString *orange = [NSString stringWithString:@"orange"];
// created for the caller, you'll have to release it when you are done
NSObject *apple = [NSString initWithString:@"apple"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.