- (NSString *)getAuthorizationHeader{ iKMAppDelegate *delegate = (iKMAppDelegate *)[UIApplication sharedApplication].delegate; NSString *header = [NSString stringWithFormat:@"Bearer %@",delegate.appDataObject.oauth2AcessToken]; return header; }
这个方法会在XCode9中收到警告
[UIApplication delegate] must be called from main thread only
解决方法
在主线程上无法访问UIApplication的委托,但您可以使用dispatch_sync轻松完成
- (NSString *)getAuthorizationHeader{ __block iKMAppDelegate *delegate; if([NSThread isMainThread]) { delegate = (iKMAppDelegate *)[UIApplication sharedApplication].delegate; } else { dispatch_sync(dispatch_get_main_queue(),^{ delegate = (iKMAppDelegate *)[UIApplication sharedApplication].delegate; }); } NSString *header = [NSString stringWithFormat:@"Bearer %@",delegate.appDataObject.oauth2AcessToken]; return header; }
与dispatch_async相反,dispatch_sync函数将一直等到它传递的块完成后再返回.
使用dispatch_sync,有必要检查是否未从主线程执行该函数,这会导致死锁.