在尝试重用现有 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 并结束这个问题,但是不能重用旧数组让我很恼火。可能是什么问题呢?