How to avoid memory leaks in such a relationship?
@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"];
Node *child = [[Node alloc] initWithObject:@"bar"];
[root setChild:child];
[root release];
[child release];
If you do not know that the beginning rootshould be dealloc'd, you only have to do what you no longer need, how and where does the link count drop to zero?
Also, can the Leaks app detect this as a leak? I suspect that I may have been bitten by this, as I am trying to identify what seems to be a leak, but the Leaks claim that I have no leaks. Since the child still refers to the parent, and vice versa, I dare to say that leaks believe that objects still refer and therefore do not leak.
source
share