上代码,这是我在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的时候也能释放了。
这么理解有问题么?(不晓得我说明白了没有,还忘各路大神出来解惑)
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.
penAnimation 默认情况下会 removedOnCompletion,因此penAnimation会被回收,delegate 会 release.
如果removedOnCompletion = NO,你需要自己release penAnimation
5楼 @akwei 多谢回复,多问一句,penAnimation被回收的时候, delegate不是先要被release掉么,然后系统释放penAnimation。而这个时候delegate 保持了强引用。系统为了打破这个retain cycle 是不是做了delegate =nil 这样的操作以保证penAnimation可以顺利释放。是这么理解吧。(removeOnCompletion == Yes的时候)。