I’m trying to return a value in a method that contains an animation block. The code I have below works perfectly fine, but it seems like there should be a better or cleaner way to do it. Is there a better way to do this?
+ (BOOL) flipImageAndTextForView:(UIView *) viewFlipImageAndText IsImageDisplayed:(BOOL) imageFlipDisplayed flipTextView:(UITextView *) textViewDonate flipImage: (UIImageView *)pictureImage{
__block BOOL tempBool;
[UIView transitionWithView:viewFlipImageAndText
duration:0.3f
options:UIViewAnimationOptionTransitionFlipFromLeft
animations:^(void) {
if (imageFlipDisplayed)
{
[viewFlipImageAndText bringSubviewToFront:textViewDonate];
tempBool = FALSE;
}
else
{
[viewFlipImageAndText bringSubviewToFront:pictureImage];
tempBool = TRUE;
}
}
completion:^(BOOL finished) {
NSLog(@"Done!");
}];
if(tempBool)
{
return TRUE;
}
else{
return FALSE;
}
}
Your code has a race condition because you can’t guarantee that tempBool will be set correctly before your
flipImageAndTextForView:...method returns.transitionWithView:duration:options:animations:completion:does not block. In any case the following lines:should have just been replaced with:
If it works the way you wrote it and not the second way, that is just another symptom of the inherent race condition here.
The best thing to do is to not structure your code like this at all. Either test
imageFlipDisplayedoutside the animation block altogether or else use the completion block oftransitionWithView:duration:options:animations:completion:to send a message to somewhere else with the information you need when the animation is complete.