//聯系人:石虎QQ: 1224614774昵稱:嗡嘛呢叭咪哄
一、概念
代碼里面有時候會把將要執行的內容放到主線程里面執行,但如果已經是主線程里面的代碼調用dispatch_async的時候偶爾會出現crash,所以就需要判斷是否已經在主線程里面了。通常的做法類似于下面所代碼:
以下是C接口:
voidWXPerformBlockSyncOnMainThread(void(^_Nonnullblock)())
{
if(!block)return;
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安全的分發任務到主線程里面運行但是這個的問題是,宏里面的block是無法打斷點調試的,
- (void)sendBatchCancelRequestWithOrderIds:(NSArray *)orderIds {
NSMutableString *orderIdsStr = [[NSMutableString alloc] initWithCapacity:orderIds.count];
for(NSString *stringinorderIds) {
[orderIdsStr appendFormat:@"%@,",string];
}self.orderIds = [orderIdsStr copy];}