0

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

RK-
  • 12,099
  • 23
  • 89
  • 155
  • Similar question: [http://stackoverflow.com/questions/791322/retain-cycles-why-is-that-such-a-bad-thing](http://stackoverflow.com/questions/791322/retain-cycles-why-is-that-such-a-bad-thing) – Michael Kessler Jul 10 '10 at 15:16

2 Answers2

3

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.

Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
  • Hi Georg Fritzche, Thanks for the wonderful example. I read the Weak references you have referred. And how do you implement weak reference in case of the example you have provided above? – RK- Jul 13 '10 at 04:27
  • @Krishnan: You can use a different container that doesn't use strong references. For `CFMutableArray` (which is toll-free bridged to `NSMutableArray`) you could set the `retain` and `release` functions to `NULL` - see [here](http://developer.apple.com/mac/library/documentation/CoreFoundation/Reference/CFArrayRef/Reference/reference.html#//apple_ref/doc/c_ref/CFArrayCallBacks). That way you get a weak referencing array. – Georg Fritzsche Jul 13 '10 at 13:54