iOS - 确保在主线程上执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11582223/
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 19:21:01  来源:igfitidea点击:

iOS - Ensure execution on main thread

iosxcodemultithreadingmultitaskingshared-resource

提问by user236739

I want to know how to call my functionon the main thread.

我想知道如何function主线程上调用 my 。

How do I make sure my functionis called on the main thread?

如何确保function主线程上调用my ?

(this follows a previous questionof mine).

(这是我之前的一个问题)。

采纳答案by Amy Worrall

there any rule I can follow to be sure that my app executes my own code just in the main thread?

我可以遵循什么规则来确保我的应用程序仅在主线程中执行我自己的代码?

Typically you wouldn't need to do anything to ensure this — your list of things is usually enough. Unless you're interacting with some API that happens to spawn a thread and run your code in the background, you'll be running on the main thread.

通常你不需要做任何事情来确保这一点——你的清单通常就足够了。除非您正在与某些 API 进行交互,而这些 API 恰好会产生一个线程并在后台运行您的代码,否则您将在主线程上运行。

If you want to be really sure, you can do things like

如果你想真正确定,你可以做这样的事情

[self performSelectorOnMainThread:@selector(myMethod:) withObject:anObj waitUntilDone:YES];

to execute a method on the main thread. (There's a GCD equivalent too.)

在主线程上执行一个方法。(也有一个 GCD 等价物。)

回答by shoughton123

This will do it:

这将做到:

[[NSOperationQueue mainQueue] addOperationWithBlock:^ {

   //Your code goes in here
   NSLog(@"Main Thread Code");

}];

Hope this helps!

希望这可以帮助!

回答by CarlJ

When you're using iOS >= 4

当您使用 iOS >= 4 时

dispatch_async(dispatch_get_main_queue(), ^{
  //Your main thread code goes in here
  NSLog(@"Im on the main thread");       
});

回答by Sean Danzeiser

i think this is cool, even tho in general its good form to leave the caller of a method responsible for ensuring its called on the right thread.

我认为这很酷,即使一般来说,让方法的调用者负责确保在正确的线程上调用它是一种很好的形式。

if (![[NSThread currentThread] isMainThread]) {
    [self performSelector:_cmd onThread:[NSThread mainThread] withObject:someObject waitUntilDone:NO];
    return;
}