async method
1 2 3 4 5 6 7 8 9 10 11 12 13 |
//Original asynchronous method - (void)executeInBackgroundWithCompletion:(void(^)(void))completion { NSOperationQueue* callbackQueue = [NSOperationQueue currentQueue]; [[[NSOperationQueue alloc] init] addOperationWithBlock:^{ //do something that takes a long time [callbackQueue addOperationWithBlock:^{ if (completion) { completion(); } }]; }]; } |
sync version
1 2 3 4 5 6 7 8 9 10 11 |
//Synchronous version - (void)executeInBackgroundAndWait { dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); [self executeInBackgroundWithCompletion:^{ dispatch_semaphore_signal(semaphore); }]; while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW)) { [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0]]; }; } |