xcode iOS -确保在主线程上执行[重复]

mv1qrgav  于 2022-12-24  发布在  iOS
关注(0)|答案(4)|浏览(188)
    • 此问题在此处已有答案**:

(13个答案)
九年前就关门了。
我想知道如何在 * 主线程 * 上调用我的function
如何确保在 * 主线程 * 上调用function

  • (这是我之前的一个question)。*
tct7dpnv

tct7dpnv1#

这将做到这一点:

[[NSOperationQueue mainQueue] addOperationWithBlock:^ {

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

}];
ss2ws0br

ss2ws0br2#

使用iOS时〉= 4

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

bmvo0sr53#

有什么规则我可以遵循,以确保我的应用程序只在主线程中执行我自己的代码?
通常情况下,你不需要做任何事情来确保这一点--你的列表通常就足够了。除非你与某个API交互,而该API碰巧会产生一个线程并在后台运行你的代码,否则你将在主线程上运行。
如果你想真正确定,你可以这样做

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

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

yvfmudvl

yvfmudvl4#

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

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

相关问题