Tutorial: Run a Block of Code After a Delay

LED Baseball Pitch
For the longest time I’ve wanted to know how to pause the app or wait a certain amount of time before running a block of code. This is often useful for when you’re doing simple animations or if you need to wait before updating the UI. Take the example to the right, in the LED Baseball game I needed to find a way to animate the pitches from the mound to home plate. The LEDs images are in set spots, and for the effect of a pitch they need to blink on and off in sequence, sometimes at different speeds depending on the pitch.

The best way to implement this code block is to implement a category that can be reused in any of your projects.
The following code is credited to Duncan C.

The header file: (filename = NSObject+performBlockAfterDelay.h)

//
//  NSObject+performBlockAfterDelay.h
//
//  Copyright (c) 2012 WareTo. May be used by anyone, free of license, as 
//  long as this copyright notice remains.
//

@interface NSObject (performBlockAfterDelay)

- (void) performBlock: (dispatch_block_t) block
           afterDelay: (NSTimeInterval) delay;

@end

The .m file: (filename = NSObject+performBlockAfterDelay.m)

//
//  NSObject+performBlockAfterDelay.m
//  ChromaKey
//
//  Copyright (c) 2012 WareTo. May be used by anyone, free of license, as 
//  long as this copyright notice remains.
//

#import "NSObject+performBlockAfterDelay.h"

@implementation NSObject (performBlockAfterDelay)

- (void) performBlock: (dispatch_block_t) block
           afterDelay: (NSTimeInterval) delay;
{
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delay * NSEC_PER_SEC), dispatch_get_current_queue(), 
                 block);
}
@end

To use it, just add the .m and .h files above to your project.
Then add a #import at the top of any .m file that needs this method:

#import "NSObject+performBlockAfterDelay.h"

Here’s a sample of the code in action for a fastball in LED Baseball.

[self performBlock:^{led1.hidden = NO;} afterDelay: .75];
[self performBlock:^{led1.hidden = YES;led2.hidden = NO;} afterDelay: .15];
[self performBlock:^{led2.hidden = YES;led3.hidden = NO;} afterDelay: .225];
[self performBlock:^{led3.hidden = YES;led4.hidden = NO;} afterDelay: .3];
[self performBlock:^{led4.hidden = YES;led7.hidden = NO;} afterDelay: .375];
[self performBlock:^{led7.hidden = YES;led8.hidden = NO;} afterDelay: .45];
[self performBlock:^{led8.hidden = YES;led9.hidden = NO;} afterDelay: .525];

By running a series of blocks in a row, each LED is shown, then hidden after a set delay.

I hope this code helps you as much as it did me, I’ll be using this category anytime I need to “pause”.