objective-c - Objective-C,NSThread分离与performSelectorInBackground

标签 objective-c multithreading nsthread

两者之间有什么区别?

 [NSThread detachNewThreadSelector:@selector(method) toTarget:self withObject:nil];
 [self performSelectorInBackground:@selector(method) withObject:nil];

我通常使用第二种方法来产生新线程。
但是我想知道,如果我像下面的方法所示两次调用它,那将会发生什么呢?另外,如果我有一个标签菜单,并且每个菜单都产生一个线程,那么我应该使用哪个线程?
 [self performSelectorInBackground:@selector(method1) withObject:nil];
 [self performSelectorInBackground:@selector(method2) withObject:nil];

最佳答案

它们是相同的。这是official documentation在该主题上必须说的:

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];

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.”



至于如果这样做,会发生什么:
[self performSelectorInBackground:@selector(method1) withObject:nil];
[self performSelectorInBackground:@selector(method2) withObject:nil];

...您将产生两个新线程,其中一个开始在method1处开始执行,其中一个开始在method2处开始执行。线程可以同时执行(即第二个线程在开始执行之前不会等待第一个线程终止)。

关于objective-c - Objective-C,NSThread分离与performSelectorInBackground,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5372637/

相关文章:

objective-c - 在 UIView 中实现 ZBar 二维码阅读器

java - Spring Boot Async方法如何使用ThreadPool处理请求

Java 线程和时序 : Nedd opinions on implementation

java - 为什么使用多线程 ping IP 段时得到不同的结果?

swift - Xcode 9.0 中的线程问题

ios - 通过 AFNetworking 中的参数的对象数组

objective-c - 检测线段是否与正方形相交

iPhone - 帮助使用 MBProgressHUD、Sudzc、Web 服务和 NSThread

ios - 在 Swift 中创建带参数的线程?

objective-c - NSTableView 右键单击​​行索引