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

Spa*_*Dog 0 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];
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

}
Run Code Online (Sandbox Code Playgroud)

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

如何检索该号码?

谢谢你的帮助.

ken*_*ytm 7

有关如何获取整数的信息,请参阅@DyingCactus的答案.

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

因此,当你表演

[(NSNumber*)context intValue];
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

(b)传递一个malloc-ed内存,并free在animationDidStop中:

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