Iphone - 如何将参数传递给animationDidStop?

时间:2010-02-19 15:20:57

标签: iphone iphone-sdk-3.0

我有这种方法......

- (void) helloThere: (int) myValue {

  // I am trying to pass myValue to animationDidStop
  [UIView beginAnimations:nil context:[NSNumber numberWithInt: myValue]];
  [UIView setAnimationDuration:1.0];
  [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
  [UIView setAnimationDelegate:self];

  // do stuff

  [UIView commitAnimations];
}

然后我试图在animationDidStop上检索myValue ...

- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {

  int retrievedValue = (int)context; //??? not giving me the right number

}

但retrieveValue给了我一个与原始myValue无关的数字......

如何检索该号码?

感谢您的帮助。

2 个答案:

答案 0 :(得分:7)

请参阅@DyingCactus的答案,了解如何获取整数。

然而,OP的代码在上下文中存在严重问题。由于上下文的类型是void*,UIKit不会指望你将ObjC对象传递给它,因此不会保留NSNumber。

因此,当你执行

[(NSNumber*)context intValue];

在animationDidStop中几乎可以肯定你会得到一些疯狂的数字或崩溃。

有两种类似的方法可以解决这个问题。

(a)传递保留计数为+1的对象,并在animationDidStop中将其释放:

[UIView beginAnimations:nil context:[[NSNumber alloc] initWithInt:myValue]];
....
int retrievedValue = [(NSNumber*)context intValue];
[(NSNumber*)context release];

(b)传递malloc个内存,并在animationDidStop中传递free

int* c = malloc(sizeof(*c));
*c = myValue;
[UIView beginAnimations:nil context:c];
....
int retrievedValue = *(int*)context;
free(context);

答案 1 :(得分:4)

您正在将NSNumber置于上下文中,因此请按以下方式检索它:

int retrievedValue = [(NSNumber *)context intValue];