【发布时间】:2011-01-08 21:20:14
【问题描述】:
在尝试重用现有 NSMutableArray(以节省内存)时,我遇到了一些泄漏(由 Instruments 观察到)。
基本上我正在创建一个 NSMutableArray,用对象 (UIImages) 填充它并将它传递给另一个保留它的对象。但是,我现在需要再次使用 NSMutableArray。我想我会释放它的所有对象,清空它,一切都会好起来的,但 Instruments 会从该方法报告一个 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];
为了清楚起见,我的按钮初始化方法如下所示:
- (id)initWithFrame:(CGRect)frame
images:(NSArray *)imageArray
{
if(self = [super initWithFrame:frame]) {
myImageArray = [[NSArray arrayWithArray:imageArray] retain];
}
return self;
}
我知道我可以创建一个新的 NSMutableArray 并结束这个问题,但不能重用旧数组让我很恼火。可能是什么问题?
【问题讨论】:
标签: objective-c cocoa release nsmutablearray reusability