使用NSObject生成线程
在iOS和Mac OS X v10.5及更高版本中,所有对象均具有生成新线程并使用其执行其方法之一的能力. performSelectorInBackground:withObject:方法创建一个新的分离线程,并将指定的方法用作新线程的入口点.例如,如果您有某个对象(由变量myObj表示),并且该对象具有要在后台线程中运行的名为doSomething的方法,则可以使用以下代码来完成该操作:
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:
[myObj performSelectorInBackground:@selector(doSomething) withObject:nil];
调用此方法的效果与使用当前对象,选择器和参数对象作为参数调用NSThread的detachNewThreadSelector:toTarget:withObject:方法的效果相同.立即使用默认配置生成新线程并开始运行.在选择器内部,必须像配置任何线程一样配置线程.例如,如果您打算使用自动释放池(如果您不使用垃圾回收),则需要设置该线程的运行循环.有关如何配置新线程的信息,请参阅配置线程属性".
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, see "Configuring Thread Attributes."
这篇关于performSelectorInBackground是否为每个调用生成新线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!