Blog 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 Blog Posts

12/10/2014 - Instacast for Mac 2.0 Now Available
10/31/2014 - Up Next in Instacast 5
10/22/2014 - Instacast 5 available today
09/16/2014 - Updates on Instacast 5
06/27/2014 - Instacast Cloud Memberships
06/06/2014 - Instacast 4.6 and Instacast Cloud
03/26/2014 - Sharebox adds Drag & Drop sharing to the Dropbox menubar icon
01/22/2014 - Instacast 4.2 adds News Mode
01/12/2014 - Hello 2014
11/07/2013 - Instacast Available on the Mac App Store
10/23/2013 - New Payment Option: Bitcoin