Blocks instead of performSelector:withObject:afterDelay: [duplicate]

There’s no built-in way to do that, but it’s not too bad to add via a category: @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 Credit to Mike Ash for the basic implementation.

How can I retrieve a return value from a completion block?

You’re missing some basics about asynchronous development with blocks. You can’t have a dispatched block return from anywhere but its own scope. Think of each block as its own method, instead of inline code. I think what you’re looking for is something similar to this… – (void)testWithHandler:(void(^)(int result))handler { [obj somemethodwithcompeltionblock:^{ int someInt = 10; … Read more

UIButton block equivalent to addTarget:action:forControlEvents: method?

I just implemented this. It work’s like a charm! And it wasn’t even hard. typedef void (^ActionBlock)(); @interface UIBlockButton : UIButton { ActionBlock _actionBlock; } -(void) handleControlEvent:(UIControlEvents)event withBlock:(ActionBlock) action; @end @implementation UIBlockButton -(void) handleControlEvent:(UIControlEvents)event withBlock:(ActionBlock) action { _actionBlock = action; [self addTarget:self action:@selector(callActionBlock:) forControlEvents:event]; } -(void) callActionBlock:(id)sender{ _actionBlock(); } @end

How to dispatch on main queue synchronously without a deadlock?

I need to use something like this fairly regularly within my Mac and iOS applications, so I use the following helper function (originally described in this answer): void runOnMainQueueWithoutDeadlocking(void (^block)(void)) { if ([NSThread isMainThread]) { block(); } else { dispatch_sync(dispatch_get_main_queue(), block); } } which you call via runOnMainQueueWithoutDeadlocking(^{ //Do stuff }); This is pretty much … Read more

Alternatives to dispatch_get_current_queue() for completion blocks in iOS 6?

The pattern of “run on whatever queue the caller was on” is appealing, but ultimately not a great idea. That queue could be a low priority queue, the main queue, or some other queue with odd properties. My favorite approach to this is to say “the completion block runs on an implementation defined queue with … Read more

Why can’t we use a dispatch_sync on the current queue?

dispatch_sync does two things: queue a block blocks the current thread until the block has finished running Given that the main thread is a serial queue (which means it uses only one thread), if you run the following statement on the main queue: dispatch_sync(dispatch_get_main_queue(), ^(){/*…*/}); the following events will happen: dispatch_sync queues the block in … Read more