Grand Central Dispatch (GCD) 与 performSelector - 需要更好的解释 [英] Grand Central Dispatch (GCD) vs. performSelector - need a better explanation

查看:21
本文介绍了Grand Central Dispatch (GCD) 与 performSelector - 需要更好的解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中同时使用了 GCD 和 performSelectorOnMainThread:waitUntilDone,并且倾向于认为它们是可以互换的——也就是说,performSelectorOnMainThread:waitUntilDone 是 GCD C 语法的 Obj-C 包装器.我一直认为这两个命令是等效的:

I've used both GCD and performSelectorOnMainThread:waitUntilDone in my apps, and tend to think of them as interchangeable--that is, performSelectorOnMainThread:waitUntilDone is an Obj-C wrapper to the GCD C syntax. I've been thinking of these two commands as equivalent:

dispatch_sync(dispatch_get_main_queue(), ^{ [self doit:YES]; });


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

我错了吗?也就是说,performSelector* 命令与 GCD 的命令有区别吗?我已经阅读了很多关于它们的文档,但还没有看到明确的答案.

Am I incorrect? That is, is there a difference of the performSelector* commands versus the GCD ones? I've read a lot of documentation on them, but have yet to see a definitive answer.

推荐答案

performSelectorOnMainThread: 确实使用 GCD 向主线程上的对象发送消息.

performSelectorOnMainThread: does not use GCD to send messages to objects on the main thread.

文档 说该方法已实现:

- (void) performSelectorOnMainThread:(SEL) selector withObject:(id) obj waitUntilDone:(BOOL) wait {
  [[NSRunLoop mainRunLoop] performSelector:selector target:self withObject:obj order:1 modes: NSRunLoopCommonModes];
}

performSelector:target:withObject:order:modes: 上,文档说明:

此方法设置一个计时器,在下一次运行循环迭代开始时在当前线程的运行循环上执行 aSelector 消息.定时器被配置为以modes 参数指定的模式运行.当计时器触发时,线程尝试从运行循环中取出消息并执行选择器.如果 run loop 正在运行并且处于指定的模式之一,则成功;否则,定时器等待直到运行循环处于这些模式之一.

This method sets up a timer to perform the aSelector message on the current thread’s run loop at the start of the next run loop iteration. The timer is configured to run in the modes specified by the modes parameter. When the timer fires, the thread attempts to dequeue the message from the run loop and perform the selector. It succeeds if the run loop is running and in one of the specified modes; otherwise, the timer waits until the run loop is in one of those modes.

这篇关于Grand Central Dispatch (GCD) 与 performSelector - 需要更好的解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆