NSMutableArray:调用方法时的内存管理 [英] NSMutableArray: Memory management while calling methods
问题描述
在我的iOS应用中,我正在使用一个名为imageMArray的NSMutableArray.我已经设置了它的getter和setter属性并实例化了它.
In my iOS app, I am using a NSMutableArray, named imageMArray. I have set its getter and setter properties and instantiated it.
在viewDidLoad中:
imageMArray=[[NSMutableArray alloc] initWithArray:CategoryImages];
imageMArray=[self shuffleOnlyArray:imageMArray];
在ShuffleOnlyArray方法中:
NSMutableArray *destArray1 = [[NSMutableArray alloc] initWithCapacity: [sourceArray count]] ;
return destArray1;
随机播放方式:
imageMArray=[[self shuffleOnlyArray:imageMArray] retain];
Shuffle方法中似乎存在内存泄漏.
There appears to be a memory leak in the Shuffle method.
我应该释放imageMArray还是将其设置为nil?如果应该发布,应该自动发布吗?
Should I release imageMArray or set it to nil? If it should be released, should it be autoreleased?
推荐答案
imageMArray=[[NSMutableArray alloc] initWithArray:CategoryImages];
在上面的语句中,您有内存泄漏.相反,您可以像下面这样.
In the above statement, you have a memoryleak. Instead you can have like as follows.
imageMArray = [NSMutableArray arrayWithArray:CategoryImages];
在ShuffleOnlyArray方法中,返回自动释放的对象.
In ShuffleOnlyArray Method, return the autoreleased object.
NSMutableArray *destArray1 = [[NSMutableArray alloc] initWithCapacity: [sourceArray count]] ;
return [destArray1 autorelease];
但是,在获得它之后,保留(获取所有权)数组对象.
But after you get it, retain (take the ownership) the array object.
imageMArray=[[self shuffleOnlyArray:imageMArray] retain];
修改
在 shuffle
方法中,执行以下操作:
In shuffle
method, do as follows:
NSMutableArray *imageMArray1 = [imageMArray mutableCopy];
if( imageMArray )
{
[imageMArray release];
}
imageMArray=[[self shuffleOnlyArray:imageMArray1] retain];
[imageMArray1 release];
修改2:另一种解决方案:
使用 SO链接中提到的类别a>
Use the category to shuffle as mentioned in the SO link
无需创建新的和释放的数组.
No need of creating new and releasing the arrays.
这篇关于NSMutableArray:调用方法时的内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!