iOS11 SDK无法访问应用程序的Delegate

前端之家收集整理的这篇文章主要介绍了iOS11 SDK无法访问应用程序的Delegate前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
- (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,有必要检查是否未从主线程执行该函数,这会导致死锁.

猜你在找的Xcode相关文章