Iphone - how to pass a parameter to animationDidStop?
I have this method...
- (void) helloThere: (int) myValue {
// I am trying to pass myValue to animationDidStop
[UIView beginAnimations:nil context:[NSNumber numberWithInt: myValue]];
[UIView setAnimationDuration:1.0开发者_Python百科];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];
[UIView setAnimationDelegate:self];
// do stuff
[UIView commitAnimations];
}
then I am trying to retrieve myValue on animationDidStop...
- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
int retrievedValue = (int)context; //??? not giving me the right number
}
but retrievedValue is giving me a number that has nothing to do to the original myValue...
How to retrieve that number?
thanks for any help.
See @DyingCactus's answer for how to get the integer.
OP's code, however, has a serious problem on the context. Since the type of context is void*
, UIKit will not expect you to pass an ObjC object into it, so the NSNumber will not be retained.
Therefore, when you perform
[(NSNumber*)context intValue];
in animationDidStop it's almost certain that you'll get some crazy numbers or crash.
There are 2 similar ways to solve this problem.
(a) Pass the object with retain count of +1, and release it in animationDidStop:
[UIView beginAnimations:nil context:[[NSNumber alloc] initWithInt:myValue]];
....
int retrievedValue = [(NSNumber*)context intValue];
[(NSNumber*)context release];
(b) Pass a malloc
-ed memory, and free
it in animationDidStop:
int* c = malloc(sizeof(*c));
*c = myValue;
[UIView beginAnimations:nil context:c];
....
int retrievedValue = *(int*)context;
free(context);
You are putting an NSNumber in context so retrieve it like this:
int retrievedValue = [(NSNumber *)context intValue];
精彩评论