我對iOS內存管理感到困惑。我有一個具有NSMutableArray類型成員的類。當將這種類型的對象存儲在另一個數組中並將其刪除時,Instruments將顯示所有這些成員泄漏內存。這是我的流氓類的定義:如何正確地釋放一個NSMutableArray與具有一個NSMutableArray成員與NSNumber對象內的對象?
@interface Tester : NSObject {
int some;
NSMutableArray* others;
}
@property int some;
@property (nonatomic, retain) NSMutableArray* others;
-(id)init;
-(id)copy;
-(void)dealloc;
@end
這裏的流氓類的實現:
@implementation Tester
@synthesize some;
@synthesize others;
-(id)init {
self = [super init];
if(self) {
some = 0;
others = [[NSMutableArray alloc] initWithCapacity:5];
int i;
for(i = 0; i < 5; ++i) {
[others addObject:[NSNumber numberWithInt:i]];
}
}
return self;
}
-(id)copy {
Tester* cop = [[Tester alloc] init];
cop.some = some;
cop.others = [others mutableCopy]
return cop;
}
-(void)dealloc {
[others removeAllObjects];
[others release];
[super dealloc];
}
@end
這裏就是我的測試:
NSMutableArray* container = [[NSMutableArray alloc] init];
Tester* orig = [[Tester alloc] init];
int i;
for(i = 0; i < 10000; ++i) {
Tester* cop = [orig copy];
[container addObject:cop];
}
while([container count] > 0) {
[[container lastObject] release];
[container removeLastObject];
}
[container release];
運行這段代碼泄漏內存和儀器顯示泄漏存儲器分配在線:
cop.others = [others mutableCopy];
我做錯了什麼?
謝謝。這就說得通了。自儀器向我指出問題出在哪裏以後,我應該自己想清楚了。 – Mayoneez 2011-04-01 17:25:42