iOS - 确保在主线程上执行

use*_*739 72 xcode multithreading multitasking ios shared-resource

我想知道如何function主线程上调用我的.

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

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

sho*_*123 162

这样做:

[[NSOperationQueue mainQueue] addOperationWithBlock:^ {

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

}];
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • 好吧,我发现这种方式更容易,因为如果你这样做,你不必每次想要在主线程上做一些新的方法. (2认同)

Car*_*rlJ 134

当您使用iOS> = 4时

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

  • 主线冻结了!这是来源:http://stackoverflow.com/a/7817170/644629 (5认同)
  • OP就是这么清楚,如果你已经在主线程上,这不是你想要做的事情. (4认同)
  • 另请参阅http://stackoverflow.com/questions/5662360/gcd-to-perform-task-in-main-thread(您应该能够使用dispatch_async,并且在主线程上没有问题). (2认同)

Amy*_*all 46

我可以遵循任何规则,以确保我的应用程序只在主线程中执行我自己的代码?

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

如果你想确定,你可以做的事情

[self performSelectorOnMainThread:@selector(myMethod:) withObject:anObj waitUntilDone:YES];
Run Code Online (Sandbox Code Playgroud)

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


Sea*_*ser 10

我认为这很酷,甚至通常它的好形式是让一个方法的调用者负责确保它被调用正确的线程.

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


归档时间:

查看次数:

109628 次

最近记录:

10 年,6 月 前