Paul
Paul

Reputation: 109

What are "parent" and "child" objects?

I saw a question about Reference counting:

Take three objects: a grandparent, parent and child. The grandparent retains the parent, the parent retains the child and the child retains the parent. The grandparent releases the parent. Explain what happens

"a grandparent retains the parent?"

What is that mean? Like this:

Class *grandparent = [[Grandparent alloc]init];
Class *parent = [grandparent copy];
..............

Somebody help me...

Upvotes: 2

Views: 4932

Answers (3)

RMDeveloper
RMDeveloper

Reputation: 477

even if grandparent release parent. Still it leads to retain cycle between parent and child.

Unless there is some other reference to the parent or child, they both become dangle. But the retain cycle between the parent and child prevent either from being released and they become wasted memory.

A child should never retain a parent. If anything, use a weak reference in the child to maintain a reference to the parent.

Upvotes: 4

Gaurav Borole
Gaurav Borole

Reputation: 846

Here The "Grandparent" retains the "parent" and "parent" retains the "child" where as "child" retains the "parent".. Here a retain cycle is established between parent and child. After releasing the Grandparent both the parent and child become orphaned but the retain count of parent will not be zero as it is being retained by the child and hence causes a memory management issue.

Retain Cycle is the condition When 2 objects keep a reference to each other and are retained, it creates a retain cycle since both objects try to retain each other, making it impossible to release.

Upvotes: 0

Jonah
Jonah

Reputation: 17958

When discussing objects a "parent-child" relationship implies a hierarchy of objects which can be represented as a tree with parents possessing strong references to their children. If you can draw that tree of objects a "parent" would be closer to the root while a "child" would be closer to a leaf node. In general parents are created first and outlive their children.

For example:

@interface Parent : NSObject
@property(nonatomic, strong) NSObject *child;
@end

@implementation Parent

- (id)init {
  self = [super init];
  if (self) {
    self.child = [[NSObject alloc] init];
  }
  return self;
}

@end

A common example is a UIViewController which is the "parent" of it's UIView child. That view may also be the "parent" of a "child" subview making the controller the subview's "grandparent".

These relationships really describe ownership patterns which commonly appear in applications and are not absolute rules. Not every object in a real application falls into a well structured tree but it is a common pattern which appears in most applications. You might also see two objects with a common "parent" referred to as "sibling" objects.

Upvotes: 3

Related Questions