【问题标题】:How to identify CAAnimation in delegate and release controller?如何在委托和释放控制器中识别 CAAnimation?
【发布时间】:2010-12-15 16:33:08
【问题描述】:

已经见过How to identify CAAnimation within the animationDidStop delegate?,这是对它的补充。

我无法让它正常工作。我有一个动画,我想在动画结束后释放它运行的控制器。 示例:控制器从右 -> 左平移然后释放自身。

定义动画:

NSValue *end = [NSValue valueWithCGPoint:CGPointMake(800, self.view.center.y)];
NSValue *start = [NSValue valueWithCGPoint:self.view.center];

CABasicAnimation *moveAnimation;        
moveAnimation = [CABasicAnimation animationWithKeyPath:@"position"];
moveAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
moveAnimation.duration = 0.45f;

moveAnimation.fromValue = start;
moveAnimation.toValue = end;

// actually set the position
[self.view.layer setPosition:[end CGPointValue]];

moveAnimation.delegate = self;
moveAnimation.removedOnCompletion = NO;
[self.view.layer addAnimation:moveAnimation forKey:MOVING_OUT];

委托方法内部:

- (void) animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag 
{
    CAAnimation *check = [self.view.layer animationForKey:MOVING_OUT];

    if (theAnimation == check)
    {
        //[check release];
        [self release];

    }
}

如果我按原样保留此代码,我的控制器不会被释放(由于动画的保留调用)。 如果我运行[check release],我会得到message sent to deallocated instance

有谁知道怎么回事? 是否有另一种方法可以在 animationDidStop 委托中识别 CAAnimation 而无需指定 removedOnCompletion = NO

编辑: 忘了提。通过不指定 removedOnCompletion = NOanimationForKey: 将返回 NULL。因此我无法识别动画。

谢谢!

【问题讨论】:

    标签: iphone objective-c core-animation core-graphics


    【解决方案1】:

    我认为最终的原因是 CAAnimation.delegate 是一个保留属性(非常奇怪,哎呀!)。

    头文件定义为:

    /* The delegate of the animation. This object is retained for the
     * lifetime of the animation object. Defaults to nil. See below for the
     * supported delegate methods. */
    
    @property(retain) id delegate;
    

    为了让self得到释放,动画必须从layer中移除,比如:

    [self.view.layer removeAnimationForKey:@THE_ANIMATION_KEY];
    

    【讨论】:

      【解决方案2】:

      不清楚您的问题是什么,但它可能会帮助您了解CAAnimation 实例是通用 KVO 容器,因此您可以向它们添加自定义信息:

      [myAnimation setValue: @"check" forKey: @"name"];
      

      然后您可以检查:

      if ([[theAnimation valueForKey: @"name"] isEqual: @"check"])
          // ...
      

      这有帮助吗?

      【讨论】:

      • 将 KVO 内容与 removedOnCompletion 结合起来:)
      • removedOnCompletion = YES 正是我所需要的!谢谢!但要向其他人指出,我检查了文档并删除了 OnCompletion 默认为 YES,我在一些测试中无意中将其设置为 NO,以为它做了其他事情。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      相关资源
      最近更新 更多