iOS 安全地在主线程执行一个Block
//主线程同步队列 #define dispatch_main_sync_safe(block)\ if ([NSThread isMainThread]) {\ block();\ } else {\ dispatch_sync(dispatch_get_main_queue(), block);\ } //主线程异步队列 #define dispatch_main_async_safe(block)\ if ([NSThread isMainThread]) {\ block();\ } else {\ dispatch_async(dispatch_get_main_queue(), block);\ }
//用法 dispatch_main_async_safe(^{ //需要执行的代码片段; });
或者
#ifndef dispatch_main_async_safe #define dispatch_main_async_safe(block)\ if (strcmp(dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL), dispatch_queue_get_label(dispatch_get_main_queue())) == 0) {\ block();\ } else {\ dispatch_async(dispatch_get_main_queue(), block);\ } #endif