Personal Posts

I love Blocks

At the beginning I was not so sure what I should think about blocks. Is it good or bad? Now, I can't live without it anymore and I want to use it in more and more cases everyday. But also everyday I realize that the Apple SDK is missing a lot of Blocks enabled API. Apple already started to add alternative methods e.g. when animating views. But it's not nearly enough.

I quickly want to highlight a case where Blocks would really come in handy but there is no such API yet. I am talking about

- (void)performSelector:(SEL)aSelector
             withObject:(id)anArgument
             afterDelay:(NSTimeInterval)delay

I don't know about you, but I really need this sometimes. The bummer with it is, that you always have to create a new selector which clutters the code.

- (void) delayedSelector:(id)object {
  NSLog(@"test");
}

- (void) mainMethod {
  [self performSelector:@selector(delayedSelector:)
             withObject:self
             afterDelay:0.5];
}

Looks familiar? But now that we have Blocks, I really want to write:

[self performBlock:^(void) {
    NSLog(@"test")
} afterDelay:0.5];

Much more easy, less to write and elegant to read. Note also that there is no need for an additional object parameter since you can use all local variables in your block method.

Unfortunately this method is not available in the SDKs yet. But luckily for us using timers in Grand Central Dispatch, we can actually implement it ourselves.

For that purpose I started an NSObject category that implements three methods to this point:

@interface NSObject (Blocks)
- (NSString*) performBlock:(void (^)(void))block
                afterDelay:(NSTimeInterval)delay;
- (void) cancelPerformBlockWithIdentifier:(NSString*)identifier;
- (void) cancelPerformBlocks;
@end 

The current method only uses the main thread to perform the block, but feel free to also add threaded variants that perform in the background. You can download it and collaborate on GitHub.

UPDATE: Apparently I am not the only one, who thought about that. There is a BlocksKit on GitHub. Thanks @steipete for pointing this out.

June 22nd, 2011 • Permalink


More articles about Personal Posts

07/13/2011 - My Inbox Archiving Apple Script for Apple Mail
06/22/2011 - I love Blocks
04/05/2011 - Getting rid of the shadow in UIWebView
01/14/2010 - Got the keys to the new headquarter office
11/05/2009 - Snowtape at the Mac Consumer Show
11/05/2009 - iPhone Tech Talk in Hamburg
07/06/2009 - HDCrashReporter - Cocoa crash reporter class
04/01/2009 - HUD Panels are driving me nuts
03/26/2009 - Regarding MacHeist
03/07/2009 - Unboxing my new 24
02/18/2009 - How to name your lite iPhone app