如何避免像這樣的關係中的內存泄漏?Objective-C:子類父類型的循環引用泄漏?
@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
應dealloc'd,你只在乎你不再需要它,如何以及在何處並引用計數下降到零?
此外,泄漏應用程序甚至會檢測到這是泄漏?我懷疑自己可能被這件事咬了一口,因爲我試圖追查似乎是泄漏的東西,但Leaks聲稱我沒有泄漏。由於孩子仍然引用父母,反之亦然,我敢說泄漏認爲對象仍然被引用,因此不泄漏。
完美,謝謝。簡而言之,在'-setParent:'和'-dealloc'方法中使用賦值將'setParent:nil'發送給孩子。非常有意義。 – d11wtq 2010-11-14 06:37:34
對不起,還有一件事。我是否認爲這種類型的內存泄漏對於泄漏檢測工具是不可見的? – d11wtq 2010-11-14 06:38:26
我並不確定,因爲我已經使用了泄漏:( – GWW 2010-11-14 06:39:44