(メモリを節約するために)既存の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を作成してこの問題を解決できることはわかっていますが、古いアレイを再利用できないのは面倒です。何が問題なのですか?