RK-
RK-

Reputation: 12211

How Retain cycles occurs in Memory Management?

Can some explain the retain cycles problem with a sample program?

Upvotes: 0

Views: 831

Answers (2)

Georg Fritzsche
Georg Fritzsche

Reputation: 98994

Consider the following:

NSMutableArray *a = [NSMutableArray array];
NSMutableArray *b = [NSMutableArray array];
[a addObject:b];
[b addObject:a];

When b is inserted into a, b is retained, likewise a when its inserted into b. As both now have a strong reference to each other, neither will get deallocated unless you manually break the cycle by e.g. removing one from the other.

Note that the Cocoa Memory Management guide also contains a section on retain cycles and includes an explanation of weak references, which help with these problems.

Upvotes: 3

Related Questions