+[NSThread detachNewThreadSelector:toTarget:withObject:] 和 -[NSObject PerformSelectorInBackground:withObject:] 有什么区别?
它们似乎执行相当相似的任务:启动一个新线程来快速轻松地执行该选择器。但有什么区别吗?也许与内存管理有关?
They seem to perform a reasonably similar task: launching a new thread that performs that selector quickly and easily. But are there any differences? Maybe with regards to memory management?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
两者是相同的。
在 iOS 和 Mac OS X v10.5 及更高版本中,所有对象都能够生成新线程并使用它来执行其方法之一。 PerformSelectorInBackground:withObject: 方法创建一个新的分离线程,并使用指定的方法作为新线程的入口点。例如,如果您有某个对象(由变量 myObj 表示),并且该对象有一个名为 doSomething 的方法,您希望在后台线程中运行该方法,则可以使用以下代码来执行此操作
:调用此方法与调用 NSThread 的 detachNewThreadSelector:toTarget:withObject: 方法相同,并以当前对象、选择器和参数对象作为参数。使用默认配置立即生成新线程并开始运行。在选择器内部,您必须像配置任何线程一样配置线程。例如,您需要设置一个自动释放池(如果您没有使用垃圾收集)并配置线程的运行循环(如果您计划使用它)。有关如何配置新线程的信息
Both are identical.
In iOS and Mac OS X v10.5 and later, all objects have the ability to spawn a new thread and use it to execute one of their methods. The performSelectorInBackground:withObject: method creates a new detached thread and uses the specified method as the entry point for the new thread. For example, if you have some object (represented by the variable myObj) and that object has a method called doSomething that you want to run in a background thread, you could could use the following code to do that:
The effect of calling this method is the same as if you called the detachNewThreadSelector:toTarget:withObject: method of NSThread with the current object, selector, and parameter object as parameters. The new thread is spawned immediately using the default configuration and begins running. Inside the selector, you must configure the thread just as you would any thread. For example, you would need to set up an autorelease pool (if you were not using garbage collection) and configure the thread’s run loop if you planned to use it. For information on how to configure new threads
我认为它们是相同的,因为
- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg;
在 NSThread.h 的NSObject (NSThreadPerformAdditions)
类别。这还不是决定性的,但这是朝这个方向的证据。I presume they are the same, as
- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg;
is defined in NSThread.h in theNSObject (NSThreadPerformAdditions)
category. That is nothing conclusive, but that is evidence in that direction.