Is it ok accessing [UIApplication sharedApplication] from background thread?

前提是你 提交于 2021-01-28 09:33:51

问题


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;
}

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

I was thinking to change it like,

- (BOOL) isProtected {

    BOOL protectedDataAvailable = NO;

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

    return protectedDataAvailable;
}

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

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

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:


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

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

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

Unless you call isProtected from the main thread yes.

or is there any better approach?

I would stick to something like this:

- (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;
}

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



来源:https://stackoverflow.com/questions/60163972/is-it-ok-accessing-uiapplication-sharedapplication-from-background-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!