如何在UI线程中运行代码从其他线程调用它

pvl*_*spk 24 ios

在Android中,有几种方法可以在主线程中运行其他代码:

 1. Activity.runOnUiThread(Runnable r)
 2. new Handler.post(Runnable r);
 3. View.post
Run Code Online (Sandbox Code Playgroud)

iOS中有哪些类似物?

 dispatch_async(dispatch_get_main_queue(), ^{

    });
Run Code Online (Sandbox Code Playgroud)

别的什么?

提前致谢.

Ali*_*are 43

现在首选的方法是使用GCD,以及您在问题中引用的代码:

dispatch_async(dispatch_get_main_queue(), ^{
    // Your code to run on the main queue/thread
});
Run Code Online (Sandbox Code Playgroud)

如果您更喜欢使用比GCD更面向对象的方法,您也可以使用NSOperation(如a NSBlockOperation)并将其添加到[NSOperationQueue mainQueue].

[[NSOperationQueue mainQueue] addOperationWithBlock:^{
    // Your code to run on the main queue/thread
 }];
Run Code Online (Sandbox Code Playgroud)

这与dispatch_async(dispatch_get_main_queue(), …)使用普通C GCD功能更加面向Objective-C/POO的优点完全相同,但是缺点是需要为创建NSOperation对象分配内存,而你可以使用普通的C和C来避免它GCD.


我建议使用GCD,但还有其他方法,比如那些允许你从主线程调用给定对象的选择器(方法)的方法:

  • - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait (NSObject的方法,因此可以在任何对象上调用)
  • 发送- (void)performSelector:(SEL)aSelector target:(id)target argument:(id)anArgument order:(NSUInteger)order modes:(NSArray *)modes上[NSRunLoop mainRunLoop]

但是那些解决方案并不像GCD那样灵活NSOperation,因为它们只允许你调用现有方法(所以你的对象必须有一个已存在的方法并执行你想要执行的操作),而GCD或-[NSOperationQueue addOperationWithBlock:]允许你传递任意方法代码(使用块).


nor*_*DEV 5

斯威夫特 5+ 示例

DispatchQueue.main.async {
    // UI code
}


DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
    // UI code
}
Run Code Online (Sandbox Code Playgroud)