當試圖重用現有NSMutableArray(爲了節省內存)時,我得到了一些泄漏(由儀器觀察)。重用NSMutableArray
基本上我創建了一個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];
爲求清晰,我的按鈕init方法如下所示:
- (id)initWithFrame:(CGRect)frame
images:(NSArray *)imageArray
{
if(self = [super initWithFrame:frame]) {
myImageArray = [[NSArray arrayWithArray:imageArray] retain];
}
return self;
}
我知道我可以只創建一個新的NSMutableArray和這個問題是在,但它讓我很煩,不能夠只是重複使用舊陣列。可能是什麼問題呢?
+1,特別是關於數組大小的信息。 – 2010-01-25 04:03:28
非常感謝這個非常具有描述性的答案! – hwaxxer 2010-01-25 09:46:52