Skip to content

Instantly share code, notes, and snippets.

@jeremy-w
Created June 3, 2011 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremy-w/1006912 to your computer and use it in GitHub Desktop.
Save jeremy-w/1006912 to your computer and use it in GitHub Desktop.
Using `dispatch_after` to update UI regularly
// clang -framework Foundation dispatch_after_example.m -o dispatch_after_example
// Compiling with gcc requires separating declaration of b from assignment,
// but you can omit the -framework flag for GCC.
/* @author Jeremy W. Sherman
* @date 2011-06-03
*
* Demonstrates use of a recursive block to set up a repeating action
* using `dispatch_after()`.
* Assumes 10.6+ or iOS with GCD and blocks (whichever version that was).
*/
#import <Foundation/Foundation.h>
int
main(void)
{
static int times = 10;
int64_t repeatAfterSec = 1LL;
dispatch_queue_t q = dispatch_get_main_queue();
/* Need __block to have the recursive call work. */
__block dispatch_block_t b = ^{
dispatch_time_t when = dispatch_time(
DISPATCH_TIME_NOW, repeatAfterSec * NSEC_PER_SEC);
fprintf(stdout, "boom! %d\n", times);
if (--times >= 0) dispatch_after(when, q, b);
else exit(0);
};
b();
dispatch_main();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment