这样写不会retain cycle么?

morpheus1984 发布于 2013年11月07日 | 更新于 2013年11月07日
无人欣赏。

上代码,这是我在github上找画图的demo,只是觉得这段代码有点迷惑。

类名: AnimatedPathViewController

- (void) startAnimation{

[self.penLayer removeAllAnimations];

self.penLayer.hidden = NO;

CAKeyframeAnimation *penAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
penAnimation.duration = 10.0;
penAnimation.path = self.pathLayer.path;
penAnimation.calculationMode = kCAAnimationPaced;
penAnimation.delegate = self;
[self.penLayer addAnimation:penAnimation forKey:@"position"];

``}

问题就是在这里 penAnimation.delegate = self; 这里的delegate的property是retain类型的。这么写不会retain cycle么?

下面是我自己的想法:

penAnimation是本地变量,虽然其delegate=self,对self是强引用,但是AnimatedPathViewController的Instance的释放不会受其影响,该释放还是释放,这样的话penAnimation在release的时候也能释放了。

这么理解有问题么?(不晓得我说明白了没有,还忘各路大神出来解惑)

共7条回复
icodor 回复于 2013年11月07日

delegate不都应该是weak么?

morpheus1984 回复于 2013年11月07日

1楼 @icodor 不是,你可以看下文档,CAanimation的delegate是retain。不是所有的delegate都是weak(或者说assign)的。

Ben.Zhong 回复于 2013年11月07日

apple的文档中说的很清楚

CAAnimation Class Reference

Important: The delegate object is retained by the receiver. This is a rare exception to the memory management rules described in Advanced Memory Management Programming Guide.

An instance of CAAnimation should not be set as a delegate of itself. Doing so (outside of a garbage-collected environment) will cause retain cycles.

morpheus1984 回复于 2013年11月07日

3楼 @Ben.Zhong 。。。你是想说会有异常抛出?文档下面的给出例子了,也是这样的写法。

akwei 回复于 2013年11月07日

penAnimation 默认情况下会 removedOnCompletion,因此penAnimation会被回收,delegate 会 release.

如果removedOnCompletion = NO,你需要自己release penAnimation

morpheus1984 回复于 2013年11月07日

5楼 @akwei 多谢回复,多问一句,penAnimation被回收的时候, delegate不是先要被release掉么,然后系统释放penAnimation。而这个时候delegate 保持了强引用。系统为了打破这个retain cycle 是不是做了delegate =nil 这样的操作以保证penAnimation可以顺利释放。是这么理解吧。(removeOnCompletion == Yes的时候)。

akwei 回复于 2013年11月07日

retain cycle和delegate = nil 好像没有关系把,只要你release了.

登录 或者 注册
相关帖子