gpt4 book ai didi

iphone - 如何正确释放带有 NSMutableArray 成员且内部有 NSNumber 对象的对象的 NSMutableArray?

转载 作者:行者123 更新时间:2023-12-03 20:26:05 25 4
gpt4 key购买 nike

我对 iOS 内存管理感到困惑。我有一个类,它有一个 NSMutableArray 类型的成员。当将这种类型的对象存储在另一个数组中并删除它们时,Instruments 显示所有这些成员都会泄漏内存。这是我的流氓类的定义:

@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];

运行此代码会泄漏内存,并且 Instruments 显示泄漏的内存是在以下行分配的:

cop.others = [others mutableCopy];

我做错了什么?

最佳答案

您正在创建一个副本:[others mutableCopy],您拥有该副本但忘记释放。该行应该是:

cop.others = [[others mutableCopy] autorelease];

如果您让 container 数组成为 Tester 对象的唯一所有者,您的测试代码将会更加清晰:

NSMutableArray* container = [[NSMutableArray alloc] init];
Tester* orig = [[Tester alloc] init];
for (int i = 0; i < 10000; ++i)
[container addObject:[[orig copy] autorelease]];

while([container count] > 0)
[container removeLastObject];

[container release];

现在您可以删除清空容器的循环。

或者你可以跳过容器:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

Tester* orig = [[[Tester alloc] init] autorelease];
for (int i = 0; i < 10000; ++i)
[[orig copy] autorelease];

[pool drain]; // At this point all Tester objects are released

关于iphone - 如何正确释放带有 NSMutableArray 成员且内部有 NSNumber 对象的对象的 NSMutableArray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5514688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com