cod*_*ons 1 multithreading objective-c nsthread
这两者有什么不同?
[NSThread detachNewThreadSelector:@selector(method) toTarget:self withObject:nil];
[self performSelectorInBackground:@selector(method) withObject:nil];
Run Code Online (Sandbox Code Playgroud)
我通常使用第二种方法来生成一个新线程.但是我想知道如果我将这两次调用如下所示,那么将会发生什么?另外如果我有一个tabmenu并且每个菜单产生一个线程,那么我应该使用哪一个?
[self performSelectorInBackground:@selector(method1) withObject:nil];
[self performSelectorInBackground:@selector(method2) withObject:nil];
Run Code Online (Sandbox Code Playgroud)
它们完全相同.以下是官方文档对此主题的评论:
在iOS和Mac OS X v10.5及更高版本中,所有对象都能够生成新线程并使用它来执行其中一个方法.performSelectorInBackground:withObject:方法创建一个新的分离线程,并使用指定的方法作为新线程的入口点.例如,如果你有一个对象(由变量myObj表示)并且该对象有一个你想在后台线程中运行的doSomething方法,你可以使用以下代码来做到这一点:
[myObj performSelectorInBackground:@selector(doSomething)withObject:nil];
调用此方法的效果与调用detachNewThreadSelector:toTarget:withObject:NSThread的方法(当前对象,选择器和参数对象作为参数)相同.使用默认配置立即生成新线程并开始运行.在选择器内部,您必须像处理任何线程一样配置线程.例如,如果您计划使用它,则需要设置自动释放池(如果您没有使用垃圾收集)并配置线程的运行循环.有关如何配置新线程的信息,请参阅"配置线程属性".
至于如果你这样做会发生什么:
[self performSelectorInBackground:@selector(method1) withObject:nil];
[self performSelectorInBackground:@selector(method2) withObject:nil];
Run Code Online (Sandbox Code Playgroud)
...你将产生两个新线程,其中一个开始执行,method1其中一个开始执行method2.线程可以并发执行(即第二个线程不会等待第一个线程在开始执行之前终止).
| 归档时间: |
|
| 查看次数: |
6228 次 |
| 最近记录: |