【问题标题】:WARNING-[UIApplication delegate] must be used from main thread onlyWARNING-[UIApplication delegate] 只能在主线程中使用
【发布时间】:2020-02-19 08:58:24
【问题描述】:

我收到警告 [UIApplication delegate] must be used from main thread only in the below line of code

((AppDelegate *)[[UIApplication sharedApplication] 委托]).loginProfile.accessToken;

以下是我的代码。

+ (NSString *)accessTokenHashForDate:(NSDate *)date withParameters:(NSArray *)params{

    NSString *accessToken = ((AppDelegate *)[[UIApplication sharedApplication] delegate]).loginProfile.accessToken;

    NSString *paramsStr = [params componentsJoinedByString:@""];
    NSString *hashStr = [NSString stringWithFormat:@"%@%@%@%@", [CommonUtil IMEI], [date agileHashFormattedString], (!paramsStr) ? @"" : paramsStr, accessToken];
    return hashStr
}

谁能告诉我如何删除这个警告信息?

【问题讨论】:

  • 首先你不应该在应用代理上保留登录配置文件。
  • @Lu_我同意你的观点,但这是遗留代码,现在我不想更改它。
  • 所以唯一的方法是在主线程上使用应用委托,使用块来返回 hashStr 因为它将是异步的,无论如何都会有很多重构

标签: ios objective-c


【解决方案1】:
+ (NSString *)accessTokenHashForDate:(NSDate *)date withParameters:(NSArray *)params{
__block NSString *accessToken = NULL;
if ([NSThread isMainThread]) {
        accessToken = ((AppDelegate *)[[UIApplication sharedApplication] delegate]).loginProfile.accessToken;


} else {
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    dispatch_async(dispatch_get_main_queue(), ^{
        accessToken = ((AppDelegate *)[[UIApplication sharedApplication] delegate]).loginProfile.accessToken;
        dispatch_semaphore_signal(semaphore);
    });
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    dispatch_semaphore_signal(semaphore);
}
NSString *paramsStr = [params componentsJoinedByString:@""];
           NSString *hashStr = [NSString stringWithFormat:@"%@%@%@%@", [CommonUtil IMEI], [date agileHashFormattedString], (!paramsStr) ? @"" : paramsStr, accessToken];
return hashStr;

}

【讨论】:

  • 有一个比使用信号量更简单的解决方案。摆脱信号量的使用,将dispatch_async 替换为dispatch_sync
猜你喜欢
  • 1970-01-01
  • 2019-08-17
  • 1970-01-01
  • 2018-12-31
  • 2019-04-29
  • 1970-01-01
  • 1970-01-01
  • 2018-03-03
  • 1970-01-01
相关资源
最近更新 更多