iOS11 SDK可以';t访问应用程序';s代表

iOS11 SDK可以';t访问应用程序';s代表,ios,xcode,Ios,Xcode,此方法将在XCode9中得到警告 - (NSString *)getAuthorizationHeader{ iKMAppDelegate *delegate = (iKMAppDelegate *)[UIApplication sharedApplication].delegate; NSString *header = [NSString stringWithFormat:@"Bearer %@", delegate.appDataObject.oauth2AcessToke

此方法将在XCode9中得到警告

- (NSString *)getAuthorizationHeader{
    iKMAppDelegate *delegate = (iKMAppDelegate *)[UIApplication sharedApplication].delegate;
    NSString *header = [NSString stringWithFormat:@"Bearer %@", delegate.appDataObject.oauth2AcessToken];
    return header;
}

我不认为在主队列中的调度将对我的功能起作用。那么如何很好地修复此警告呢?

在调用后台函数之前,可以使用指向AppDelegate的指针。从那个指针上得到它

[UIApplication delegate] must be called from main thread only

[[MyDelegateHolder]setDelegate:[iKMAppDelegate*)[UIApplication sharedApplication].delegate];
[[MyDelegateHolder].delegate方法调用];

在主线程上不需要访问UIApplication的委托,但您可以使用
dispatch\u sync

<...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;
}
dispatch\u async
相反,
dispatch\u sync
函数将等到传递的块完成后再返回


使用
dispatch\u sync
有必要检查函数是否没有从主线程执行,这会导致死锁。

看到这个“我认为主队列中的调度不会对我的函数起作用”—为什么会这样?@mag\u zbc因为我在函数中返回了一些东西,根据委托人,很可能您的应用程序委托人的
appDataObject
,或数据对象的
OAuth2AccessToken
也不安全,无法从后台线程访问。
- (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;
}