加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 17:48:01 所属栏目:百科 来源:网络整理
导读:- (NSString *)getAuthorizationHeader{ iKMAppDelegate *delegate = (iKMAppDelegate *)[UIApplication sharedApplication].delegate; NSString *header = [NSString stringWithFormat:@"Bearer %@",delegate.appDataObject.oauth2AcessToken]; return head
- (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,有必要检查是否未从主线程执行该函数,这会导致死锁.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读