iOS Objective C: 如何将更多参数传递给 animationDidStop?

iOS Objective C: How to pass more arguments to animationDidStop?

我需要在动画停止后做一些事情,所以我将自己作为委托

CAShapeLayer* myLayer = [CAShapeLayer layer];
...
CABasicAnimation * animation;
...
animation.delegate=self;
...
[myLayer addAnimation:animation];

这只是一个解释情况的简化示例。 像往常一样,这是最后调用的方法

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag

我需要另一个参数,我不想将它作为 class 的成员,因为它会被其他方法看到。我需要将我的另一个方法作为委托,在创建动画时添加一个整数参数,以便将其作为本地参数。 示例:

-(void)myAnimationDidStop:(CAAnimation *)anim finished:(BOOL)flag index:(int) ind

有没有办法达到这个目标?

您的委托可以管理每个动画后处理所需的数据。我正在考虑一个以动画对象为键的 NSMutableDictionary:

// where you setup the animation
animation.delegate=self;
MyAnimationDataClass *myAnimationData;
[self.runningAnimations setObject: myAnimationData forKey: animation];

然后在你的委托方法回调中:

-(void)myAnimationDidStop:(CAAnimation *)anim finished:(BOOL)flag index:(int) ind {
  MyAnimationDataClass *myData = [self.runningAnimations objectForKey: anim];
  if (myData) {
    // do your postprocessing
  }  
}

您实际上可以为图层和动画对象上的任何键设置值。请注意,由于动画在添加到图层时会被复制,因此您必须在将其添加到图层之前设置值,否则您修改的对象与最终完成的对象不同。

此行为记录在 Core Animation Programming Guide:

The CAAnimation and CALayer classes are key-value coding compliant container classes, which means that you can set values for arbitrary keys. Even if the key someKey is not a declared property of the CALayer class, you can still set a value for it as follows:

// before adding the animation (because the animation get's copied)
[theAnimation setValue:yourValueHere forKey:@"yourKeyHere"];

然后在 animationDidStop:

中检索它
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    id yourExtraData = [anim valueForKey:@"yourKeyHere"];
    if (yourExtraData) {
        // do something with it
    }
}