views:

59

answers:

3

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

+1  A: 

Similar question: http://stackoverflow.com/questions/791322/retain-cycles-why-is-that-such-a-bad-thing

Michael Kessler
Thanks Micheal.
Krishnan
+3  A: 

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
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?
Krishnan
@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