开发者

Can any one explain Retain cycle with example code(Objective C) ? and How can we remove retain Cycle ?(with code)

Can any one explain Retain cycle with example code(Objective C) ? and How can we remove retain Cycle ?(with code or diagram). I know about it theoretically but i never come across su开发者_开发百科ch kind of program ? I am very curious to see, how retain cycle solved (with code or diagram) ?


Delegation is one example where you have to avoid a retain cycle by using the assign attribute on a delegate property. For example, you have a parent object which creates a child:

self.child = [[[Child alloc] init] autorelease];

So the parent has a retained reference to the child (because the property setter retains it).

Now the parent sets itself as a delegate on the child:

self.child.delegate = self;

Now, if the child retains its delegate property there is a retain cycle. Both contain references to the other and cannot be deallocated.

To avoid this the child declares the delegate property with the assign attribute:

@property (nonatomic, assign) id delegate;

This is safe because a delegate will almost always outlive the delegator. If not, the parent should set the child's delegate to nil before it goes away.


The memory management aspects of Objective-C are very well covered in many places.

Some references:

  1. http://www.otierney.net/objective-c.html#memorymanagement
  2. http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html

You might consider coming back here if you have specific solutions of which you are unsure, so that we have concrete examples to comment on. You post your code, do not hesitate if you are afraid it might look very stupid or full of mistakes. That is the best way to learn.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜