5

I have this code:

[UIView animateWithDuration:0.8
                             animations:^{ 
                                 [self methodToRun];
                             } 
                             completion:^(BOOL finished){
                                 [self anotherMethod];
                             }];

Although there's things in methodToRun, the app just doesn't wait the 0.8 seconds and proceeds to run anotherMethod. Is there any way I can simply just get to wait 0.8 seconds before running the second bit?

Andrew
  • 15,935
  • 28
  • 121
  • 203
  • what exactly is it that is being done in those two methods, and how are you determining that the completion block isn't waiting? – jscs Jun 13 '11 at 19:20

2 Answers2

9

Don't misuse an animation block like that. If you really want a delay, use the method Ken linked to or even an easier way is to use GCD (iOS 4+).

Here's an example using a delay of 0.8 like you used in your question:

dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 0.8); 
dispatch_after(delay, dispatch_get_main_queue(), ^(void){
    [self anotherMethod];
});
sudo rm -rf
  • 29,408
  • 19
  • 102
  • 161
  • It's worth noting that Andrew was told to use `animateWithDuration:animations:completion:` in [his earlier question](http://stackoverflow.com/questions/6330050/how-do-i-wait-until-an-animation-in-a-different-class-is-finished-before-continui) about the problem he's working on. He might appreciate a more in-depth explanation of why that answer constitutes "misusing" an animation block, if you are so inclined as to provide one. – jscs Jun 13 '11 at 17:52
  • I was waiting for him to give more detail, but it looks like he's figured it out anyways. – jscs Jun 13 '11 at 22:34
  • 1
    It's not a technical misuse of animation blocks, I believe sudo is just referring to the fact that is would tend to obfuscate the intended control flow. Usually something synchronized within an animation block would be pretty localized or self-explanatory. Calling out to arbitrary methods could make it more difficult to manage the code. – whitneyland Nov 03 '11 at 23:05
4

You could add a call to [NSTimer performSelector:withObject:afterDelay] instead of relying on the completion parameter.

Ken Pespisa
  • 21,989
  • 3
  • 55
  • 63