在 Android 中,有几种方法可以在主线程中运行其他代码中的一些代码:
1. Activity.runOnUiThread(Runnable r)
2. new Handler.post(Runnable r);
3. View.post
iOS 中的类似物是什么?
dispatch_async(dispatch_get_main_queue(), ^{
});
还有别的吗?
提前致谢。
最佳答案
现在首选的方法是使用 GCD,以及您在问题中引用的代码:
dispatch_async(dispatch_get_main_queue(), ^{
// Your code to run on the main queue/thread
});
如果您更喜欢使用比 GCD 更面向对象的方法,您还可以使用 NSOperation
(如 NSBlockOperation
)并将其添加到 [ NSOperationQueue mainQueue]
.
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// Your code to run on the main queue/thread
}];
这与 dispatch_async(dispatch_get_main_queue(), …)
做的事情完全相同,具有比普通 C GCD 函数更面向 Objective-C/POO 的优势,但具有创建 NSOperation
对象需要分配内存的缺点,而您可以使用纯 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:]
允许您传递任意代码(使用 block )。
关于ios - 如何在 UI 线程中运行代码,从其他线程调用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12874917/