在这样的关系中如何避免内存泄漏?
@class Node;
@interface Node : NSObject {
Node *parent;
Node *child;
id object;
}
-(id)initWithObject:(id)anObject;
-(id)object;
-(void)setChild:(Node *)aNode;
-(void)setParent:(Node *)aNode;
@end
@implementation Node
-(id)initWithObject:(id)anObject {
if (self = [self init]) {
object = [anObject retain];
}
return self;
}
-(id)object {
return object;
}
-(void)setParent:(Node *)aNode {
[parent release];
parent = [aNode retain];
}
-(void)setChild:(Node *)aNode {
[child release];
child = [aNode retain];
[child setParent:self];
}
-(void)dealloc {
[child release];
[parent release];
[super dealloc];
}
@end
Node *root = [[Node alloc] initWithObject:@"foo"]; // root retain = 1
Node *child = [[Node alloc] initWithObject:@"bar"]; // child retain = 1
[root setChild:child]; // child retain = 2, root retain = 2
[root release]; // root retain = 1
[child release]; // child retain = 1
/* Leaking! */
如果您不知道root
应该预先解除分配,您只关心您不再需要它,引用计数如何以及在何处降至零?
此外,Leaks 应用程序甚至会将其检测为泄漏吗?我怀疑我可能被这个咬了,因为我试图追查似乎是泄漏的地方,但 Leaks 声称我没有泄漏。由于 child 仍然引用 parent,反之亦然,我敢说 Leaks 认为对象仍然被引用,因此不会泄漏。