Monday, December 9, 2013

Retain Cycles in iOS (iPhone)

Retain Cycles

There are two Objects P and Q. P creates Q and retains it. Q has an instance variable that points to P, retaining it. So both retain each other.


Example:-

NSMutableArray *P = [NSMutableArray array];
NSMutableArray *Q = [NSMutableArray array];
[P addObject:Q];
[Q addObject:P];
Here both P and Q has strong refernce to each other. 
Every time a reference is deleted, the count goes down, when the count gets to zero, there are no references and so the object can be deleted.
Neither will get deallocated unless you manually break the cycle by e.g. removing one from the other.

Often avoided because they can make it tricky to ensure you haven't got memory leaks.



 If you have a cycle, You may have a group of objects and you don't want them any more, so you drop the only reference you have to these objects, but because there is a cycle the objects reference each other. This means their reference counts never go to zero, and they don't get deleted. This is a memory leak.

Garbage Collection handles this retain cycle without memory leaks

0 comments:

Post a Comment

About

Powered by Blogger.