- (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而且我不认为在主队列中的调度会对我的功能起作用。那么如何修复这个警告呢?
发布于 2017-07-24 16:32:27
不需要在主线程上访问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,有必要检查函数是否不是从主线程执行的,这将导致死锁。
发布于 2017-07-24 16:19:05
您可以在调用后台函数之前获取指向AppDelegate的指针。并从那个指针中获取它。
<...Main thread in app...>
[[MyDelegateHolder holder] setDelegate: (iKMAppDelegate *)[UIApplication sharedApplication].delegate];
<...RunBackground task...>
[[MyDelegateHolder holder].delegate methodCall];
<...In MyDelegateHolder's delegate method ....>
- (iKMAppDelegate*)delegate
{
if (self.delegate == nil)
{
<Assert or...>
runSyncOnMainThread(^(){//you should get delegate in sync method from the main thread
self.delegate = (iKMAppDelegate *)[UIApplication sharedApplication].delegate;
});
}
return self.delegate;
}在我的示例中,MyDelegateHolder是一个单例。
如果您需要多线程访问,在不设置委托之前,不要忘记访问锁(或将字段标记为原子)。
https://stackoverflow.com/questions/45275252
复制相似问题