views:

443

answers:

2

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];
  [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.

+4  A: 

You are putting an NSNumber in context so retrieve it like this:

int retrievedValue = [(NSNumber *)context intValue];
DyingCactus
+5  A: 

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);
KennyTM
Thanks for the additional info.
DyingCactus
perfect, thanks!!!!!!
Digital Robot
Just curious: I don't see a selector named animationDidStop:finished:context: in the documentation. I see animationDidStop:finished: selector, but its signature is different, where the animation is a CAAnimation and the finished is a BOOL - the one in the question passes an NSString for an animation id and a number for finished and a void * for context. Am I missing something in the documentation??
Jasarien
Oh, I see. I was looking at the wrong method. The one I saw was on NSObject, and the one I was looking for is on UIView. Thanks.
Jasarien
Think I've been doing it wrong all this time... see: http://stackoverflow.com/questions/2297752/setting-animationdidstopselector-on-uiviews-animation-delegate
Jasarien