PerformSelector 方法有什么作用?
performSelector
是做什么的?创建新的 NSThread
和 performSelector
方法有什么区别?
它是如何工作的以及我们应该在哪里使用它?
What does performSelector
do? What is the difference between creating a new NSThread
and the performSelector
method?
How it works and where should we use it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
performSelector
执行选择器。换句话说,它调用了一个方法。这与运行新线程有很大不同。
我认为您最好阅读 选择器。
performSelector
executes a selector. In other words, it calls a method.It is very different from running a new thread.
I think it would be best for you to read up on selectors.
所有这些都执行相同的任务,即使
anObject
上的doStuff
方法在 current 线程上同步执行:anObject
的类未知,通常首先询问该对象是否具有-[NSObject respondsToSelector:]
的方法。IMP
(实现),然后直接调用它。如果在紧密循环中使用,有时可能比 1. 更快。只要记住; 过早的优化是邪恶的。你需要明白的是,在 Objective-C 中,方法比类/接口更重要。通常,如果对象属于特定类或符合任何协议,则不会查询该对象,这是编译器会抱怨的。在运行时,您可以查询特定的方法。
简而言之:你是什么并不重要,重要的是你能做什么。
作为一种方便,
NSObject
也有几个performSelector
的兄弟姐妹,它们是异步。最值得注意的是:performSelector:withObject:afterDelay:
- 在延迟后在当前线程上执行该方法。performSelectorInBackground:withObject:
- 在新的后台线程上执行该方法。performSelectorOnMainThread:withObject:waitUntilDone:
- 在主线程上执行该方法。performSelector:onThread:withObject:waitUntilDone:
- 在任何线程上执行该方法。异步执行器都依赖于 NSRunLoop 来运行。这不是您需要担心的事情,除非您自己生成线程。如果这样做,那么您还需要运行新线程运行循环。现在就跳过这个吧。
All of these perform the same task, that is make the
doStuff
method onanObject
execute synchronously on the current thread:anObject
is unknown, usually used by first asking if the object has the method with-[NSObject respondsToSelector:]
.IMP
(implementation) for a method, and then call it directly. Can sometimes be faster than 1. if used in a tight loop. Just remember; premature optimization is evil.What you need to grasp is that in Objective-C methods are more important than classes/interfaces. Usually you do not query an object if it belongs to a particular class, or conforms to any protocol, that is for the compiler to complain about. At run-time you instead query for specific methods.
In short: It does not matter what you are, just what you can do.
As a convenience
NSObject
also have several siblings toperformSelector
that are asynchronios. Most notably:performSelector:withObject:afterDelay:
- To execute the method on the current thread after a delay.performSelectorInBackground:withObject:
- To execute the method on a new background thread.performSelectorOnMainThread:withObject:waitUntilDone:
- To execute the method on the main thread.performSelector:onThread:withObject:waitUntilDone:
- To execute the method on any thread.The asynchronous performers all depend on a
NSRunLoop
to function. This is not something you need to worry about unless you spawn a thread yourself. If you do then you need to also run the new threads run loop. Just skip that for now.