重用NSMutableArray

hwa*_*xer 1 cocoa release objective-c reusability nsmutablearray

在尝试重用现有的NSMutableArray时(为了节省内存),我得到了一些泄漏(由Instruments观察到).

基本上我正在创建一个NSMutableArray,用对象(UIImages)填充它并将它传递给另一个保留它的对象.但是,我现在需要再次使用NSMutableArray.我想我会释放它的所有对象,清空它,一切都会好的,但是仪器报告了一个CALayer泄漏的对象(??),该方法看起来如下:

NSString *fileName;
NSMutableArray *arrayOfImages = [[NSMutableArray alloc] init];

// fill the array with images
for(int i = 0; i <= 7; i++) {
    fileName = [NSString stringWithFormat:@"myImage_%d.png", i];
    [arrayOfImages addObject:[UIImage imageNamed:fileName]];
}

// create a button with the array
aButton = [[CustomButtonClass buttonWithType:UIButtonTypeCustom] 
                   initWithFrame:someFrame
                   imageArray:arrayOfImages];

// release its objects
for(int i = 0; i < [arrayOfImages count]; i++) {
    [[arrayOfImages objectAtIndex:i] release];
}
// empty array
[arrayOfImages removeAllObjects];

// fill it with other images
for(int i = 0; i <= 7; i++) {
    fileName = [NSString stringWithFormat:@"myOtherImage_%d.png", i];
    [arrayOfImages addObject:[UIImage imageNamed:fileName]];
}
// create another button with other images (same array)
aSecondButton = [[CustomButtonClass buttonWithType:UIButtonTypeCustom] 
                   initWithFrame:someFrame
                   imageArray:arrayOfImages];

[arrayOfImages release];
Run Code Online (Sandbox Code Playgroud)

为清楚起见,我的按钮init方法如下所示:

- (id)initWithFrame:(CGRect)frame 
      images:(NSArray *)imageArray
{
    if(self = [super initWithFrame:frame]) {
        myImageArray = [[NSArray arrayWithArray:imageArray] retain];
    }
return self;
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以创建一个新的NSMutableArray并完成这个问题,但是我不能再重复使用旧的数组.可能是什么问题呢?

bbu*_*bum 6

在尝试重用现有的NSMutableArray时(为了节省内存),我得到了一些泄漏(由Instruments观察到).

一个数组需要很少的内存; 每个指针存储4个字节(在32位系统上)+一小部分开销.重复使用数组来尝试节省内存是浪费时间,除了最特殊的情况.

// release its objects
for(int i = 0; i < [arrayOfImages count]; i++) {
    [[arrayOfImages objectAtIndex:i] release];
}
// empty array
[arrayOfImages removeAllObjects];
Run Code Online (Sandbox Code Playgroud)

你没有保留这些物品,因此你不应该释放它们!在上述情况之后,您的应用程序没有崩溃,这表明您可能会过度保留其他位置的对象.

我知道我可以创建一个新的NSMutableArray并完成这个问题,但是我不能再重复使用旧的数组.可能是什么问题呢?

该代码中没有任何东西可以作为内存泄漏而出现.恰好相反; 你过度释放物体了.

以上表明你真的需要重新审视内存管理指南,因为重新使用数组而不是发布数组并创建一个新数组实际上与此问题没有任何关系.