Pierre Bernard

My little hideout on the net

HHBlockPerform revisited

The first post on the subject prompted Ben to comment: "Helpful tip: Just capture the object being messaged using the block's scope. No need for the extra "owner" parameters and whatnot." Right he is.

typedef void (^HHPerformBlock)();


@interface NSObject (HHBlockPerform)

- (
void)performAfterDelay:(NSTimeInterval)delay block:(HHPerformBlock)block;
- (
void)performOnMainThreadWait:(BOOL)wait block:(HHPerformBlock)block;

@end


@implementation NSObject (HHBlockPerform)

- (
void)performAfterDelay:(NSTimeInterval)delay block:(HHPerformBlock)block
{
[
self performSelector:@selector(runBlock:) withObject:[block copy] afterDelay:delay];
}

- (
void)performOnMainThreadWait:(BOOL)wait block:(HHPerformBlock)block
{
[
self performSelectorOnMainThread:@selector(runBlock:) withObject:[block copy] waitUntilDone:wait];
}

- (
void)runBlock:(HHPerformBlock)block
{
block();

[block
release];
}

@end

It does not get any simpler than this:

[self performAfterDelay:0.2f block:^ {
[containerView
replaceSubview:currentNavigationBarView with:navigationBarView];
}];

[UPDATE October9, 2009] While I agree that the (id owner) argument is not strictly necessary, I do prefer that API and will keep using it. Indeed, it allows for reusable blocks which refer to owner much like you would refer to self in the delyed method call.
Comments