检测代码是否在 Objective-C 的主线程上运行的正确方法是什么?(iOS)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4230420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:07:39  来源:igfitidea点击:

What is the proper way to detect if code is running on the main thread in Objective-C? (iOS)

iphoneobjective-cmultithreadingios

提问by Cameron Hotchkies

My code needs to guarantee a certain operation run on the main thread, but calls may come from background threads.

我的代码需要保证某个操作在主线程上运行,但调用可能来自后台线程。

To detect situations in the background I was using the following:

为了检测背景中的情况,我使用了以下内容:

- (void)selectorToRunInMainThread:(id)arguments
{
    // push to main thread
        if ([NSRunLoop currentRunLoop] != [NSRunLoop mainRunLoop])
        {
            [self performSelectorOnMainThread:@selector(selectorToRunInMainThread:) withObject:arguments waitUntilDone:NO];
            return;
        }

    /*
    ... function content ...
    */
}

This works on iOS 4 and iOS 3.2 but not on iOS 3.1.3 and earlier. In these earlier versions, the function will keep getting called in an endless loop.

这适用于 iOS 4 和 iOS 3.2,但不适用于 iOS 3.1.3 及更早版本。在这些早期版本中,该函数将在无限循环中不断被调用。

Changing the comparison to:

将比较更改为:

if (![[NSRunLoop currentRunLoop] isEqualTo:[NSRunLoop mainRunLoop]])

if (![[NSRunLoop currentRunLoop] isEqualTo:[NSRunLoop mainRunLoop]])

has no effect, they still never compare to the same value.

没有效果,它们仍然永远不会与相同的值进行比较。

I found a solution that appears to be working, but I'd like to see what other people suggest first.

我找到了一个似乎有效的解决方案,但我想先看看其他人的建议。

回答by bbum

[NSThread isMainThread]and, if not, dispatch via any of a number of mechanisms to the main thread (what you have is fine).

[NSThread isMainThread]并且,如果没有,则通过多种机制中的任何一种调度到主线程(您所拥有的都很好)。