可以从后台线程访问 [UIApplication sharedApplication] 吗? [英] Is it ok accessing [UIApplication sharedApplication] from background thread?

查看:142
本文介绍了可以从后台线程访问 [UIApplication sharedApplication] 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理 Objective-C 时,我可能需要在某些后台线程中获取 protectedDataAvailable 状态.

While working on Objective-C, I need to get the protectedDataAvailable status possibly inside some background threads.

- (BOOL) isProtected {
    BOOL protectedDataAvailable = [[UIApplication sharedApplication] isProtectedDataAvailable];
    return protectedDataAvailable;
}

当我访问 [UIApplication sharedApplication] 时,我怀疑代码块应该在主队列中运行.我该怎么做?

As I am accessing [UIApplication sharedApplication], I suspect that the code block should run in main queue. How can I do so?

我想改变它,

- (BOOL) isProtected {

    BOOL protectedDataAvailable = NO;

    dispatch_sync(dispatch_get_main_queue(), ^{
        protectedDataAvailable = [[UIApplication sharedApplication] isProtectedDataAvailable];
    });

    return protectedDataAvailable;
}

问题 1: 代码应该在主队列/UI 线程内运行吗?

Question 1: Should the code be run inside main queue/ UI Thread?

问题 2:如果是,我更改后的代码能解决问题吗?或者有什么更好的方法吗?

Question 2: If yes, will my changed code resolve the problem? or is there any better approach?

我问这个问题的原因是,即使我在主队列同步访问UIApplication,当块从主线程它会崩溃.我该如何处理这个问题?

The reason I am asking this question is, even if I access the UIApplication on main queue synchronously, when the block gets called from main thread it gets crash. How can I deal with this problem?

推荐答案

问题 1:代码是否应该在主队列/UI 线程内运行?

Question 1: Should the code be run inside main queue/ UI Thread?

绝对是的,因为如果您在 Xcode 上使用主线程检查器运行您的应用程序,则在从后台线程访问时会将调用 UIApplication sharedApplication 高亮显示为问题

Definitely yes because if you run your app with the main thread checker on Xcode will highlight calls UIApplication sharedApplication as issues when accessed from a background thread

问题 2:如果是,我更改后的代码会解决问题吗?

Question 2: If yes, will my changed code resolve the problem?

除非你从主线程调用 isProtected 是.

Unless you call isProtected from the main thread yes.

或者有更好的方法吗?

我会坚持这样的事情:

- (BOOL)isProtected
{
    __block BOOL protectedDataAvailable = NO;

    if ([NSThread isMainThread])
    {
        protectedDataAvailable = [[UIApplication sharedApplication] isProtectedDataAvailable];
    }
    else
    {
        dispatch_sync(dispatch_get_main_queue(), ^{

            protectedDataAvailable = [[UIApplication sharedApplication] isProtectedDataAvailable];
        });
    }

    return protectedDataAvailable;
}

正如 Alejandro Ivan 在评论中指出的,您可以使用简单的 dispatch_sync

As Alejandro Ivan pointed in the comment instead of using a semaphore you can resort to simple dispatch_sync

这篇关于可以从后台线程访问 [UIApplication sharedApplication] 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆