title: Objective-C: Child-parent type circular references, leaking?
body: <p>How does one avoid memory leaks in a relationship like this?</p>
  
  <pre><code>@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
  </code></pre>
  
  <hr>
  
  <pre><code>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! */
  </code></pre>
  
  <p>If you don't know up-front <code>root</code> should be dealloc'd, you only care that you no longer need it, how and where does the reference count drop to zero?</p>
  
  <p>Also, would the Leaks application even detect this as a leak?  I suspect I may have been bitten by this as I'm trying to track down what seems to be a leak, but Leaks claims I have no leaks.  Since child still references parent, and vice-versa, I dare say Leaks considers the objects to still be referenced, and therefore not leaking.</p>