Iphone-如何将参数传递给animationDidStop?
我有这个方法Iphone-如何将参数传递给animationDidStop?,iphone,iphone-sdk-3.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:@se
- (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上检索我的值
- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
int retrievedValue = (int)context; //??? not giving me the right number
}
但是retrievedValue给了我一个与原始myValue无关的数字
如何检索该号码
感谢您的帮助。您正在将NSNumber放入上下文中,请按如下方式检索它:
int retrievedValue = [(NSNumber *)context intValue];
有关如何获取整数,请参见的答案
然而,OP的代码在上下文上有一个严重的问题。由于上下文的类型是void*
,UIKit不希望您将ObjC对象传递给它,因此NSNumber不会被保留
因此,当您执行
[(NSNumber*)context intValue];
在动画中,几乎可以肯定,你会得到一些疯狂的数字或崩溃
有两种类似的方法可以解决此问题
(a)传递保留计数为+1的对象,并在animationDidStop中释放它:
[UIView beginAnimations:nil context:[[NSNumber alloc] initWithInt:myValue]];
....
int retrievedValue = [(NSNumber*)context intValue];
[(NSNumber*)context release];
int* c = malloc(sizeof(*c));
*c = myValue;
[UIView beginAnimations:nil context:c];
....
int retrievedValue = *(int*)context;
free(context);
(b)传递一个malloc
-ed内存,然后在animationDidStop中释放它:
[UIView beginAnimations:nil context:[[NSNumber alloc] initWithInt:myValue]];
....
int retrievedValue = [(NSNumber*)context intValue];
[(NSNumber*)context release];
int* c = malloc(sizeof(*c));
*c = myValue;
[UIView beginAnimations:nil context:c];
....
int retrievedValue = *(int*)context;
free(context);
谢谢你提供的额外信息。只是好奇:我在文档中没有看到名为animationDidStop:finished:context:的选择器。我看到animationDidStop:finished:selector,但它的签名不同,其中动画是一个动画,finished是一个BOOL-问题中的一个传递一个NSString作为动画id,传递一个数字作为finished,传递一个void*作为上下文。我是不是在文件中遗漏了什么?哦,我明白了。我用错了方法。我看到的那个在NSObject上,我要找的那个在UIView上。谢谢。我想我一直在做错事。。。请参阅:如果您使用ARC,请不要忘记添加桥铸件<代码>[UIView beginAnimations:@“ResizeForKeyboard”上下文:(u bridge void*)@“test”]代码>和处理程序中的:[(\uuu-bridge-NSString*)上下文IsequalString:@“test”]