May 29, 2012

Blocks save the day

I’m consistently amazed how useful blocks are in Objective-C. So much so that I’ll be attempting to document useful ways that blocks can make your life easier as an iOS developer. Here’s the first of (hopefully) many posts of its kind.

Take this code

  • (void)viewDidAppear:(BOOL)animated { { UIView *viewToAnimate = ... [self performSelector:@selector(animateIt:) withObject:viewToAnimate afterDelay:1.0f]; } -(void)animateIt:(id)sender { // animate viewToAnimate }

It seems like this could be better by having the animation code where you have your selector delay setup. Well guess what? Blocks to the rescue!

@implementation NSObject (PerformBlockAfterDelay) - (void)performBlock:(void (^)(void))block afterDelay:(NSTimeInterval)delay { block = [[block copy] autorelease]; [self performSelector:@selector(fireBlockAfterDelay:) withObject:block afterDelay:delay]; } - (void)fireBlockAfterDelay:(void (^)(void))block { block(); } @end

This snippet is using category that you can #import into your class. Using this in practice you get this.

  • (void)viewDidAppear:(BOOL)animated { { UIView *viewToAnimate = ... [self performBlock:^void() { // animate viewToAnimate } afterDelay:1.0f]; }

Credit goes out to this StackOverflow thread for the tip.