Objective-C: Child-parent circular links leaking?

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"]; // 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! */

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.

+3
source share
2

, . " ", , . .

+5

, : , , , .

, , : , , -setChild:, aNode==child. child -retain, () .

, :

if (aNode != child) {
    // ... same as before
}

Node *tmp = child;
child = [aNode retain];
[tmp release];
+3

Source: https://habr.com/ru/post/1774752/


All Articles