ios nsoperation 可以依赖多个么

2026年09月28日 21:48
有1个网友回答
网友(1):

  1. NSThread

  2. 2.NSOperationQueue

  3. 3.GCD

  4. NSThread:

  5. 创建方式主要有两种:

  6. [NSThread detachNewThreadSelector:@selector(myThreadMainMethod:) toTarget:self withObject:nil];

  7. 和

  8. NSThread* myThread = [[NSThread alloc] initWithTarget:self

  9. selector:@selector(myThreadMainMethod:)

  10. object:nil];

  11. [myThread start]; //启动线程

  12. 这两种方式的区别是:前一种一调用就会立即创建一个线程来做事情;而后一种虽然你 alloc 了也 init了,但是要直到我们手动调用 start 启动线程时才会真正去创建线程。这种延迟实现思想在很多跟资源相关的地方都有用到。后一种方式我们还可以在启动线程之前,对线程进行配置,比如设置 stack 大小,线程优先级。

  13. 此外还有一种间接的方式:利用NSObject的方法

  14. performSelectorInBackground:withObject: 来创建一个线程:

  15. [myObj performSelectorInBackground:@selector(myThreadMainMethod) withObject:nil]; //在后台运行某一个方法

  16. 其效果与 NSThread 的 detachNewThreadSelector:toTarget:withObject: 是一样的。

  17. NSOperationQueue

  18. The NSOperation class is an abstract class you use to encapsulate the code and data associated with a single task. Because it is abstract, you do not use this class directly but instead subclass or use one of the system-defined subclasses (NSInvocationOperation or NSBlockOperation) to perform the actual task.

  19. 并发执行你需要重载如下4个方法

  20. //执行任务主函数,线程运行的入口函数

  21. -(void)start 

  22. //是否允许并发,返回YES,允许并发,返回NO不允许。默认返回NO

  23. -(BOOL)isConcurrent 

  24. - (BOOL)isExecuting

  25. //是否已经完成,这个必须要重载,不然放在放在NSOperationQueue里的NSOpertaion不能正常释放。

  26. - (BOOL)isFinished

比如TestNSOperation:NSOperaion 重载上述的4个方法,

声明一个NSOperationQueue,NSOperationQueue *queue = [[[NSOperationQueue alloc ] init]autorelease];

[queue addOperation:testNSoperation];

它会自动调用TestNSOperation里的start函数,如果需要多个NSOperation,你需要设置queue的一些属性,如果多个NSOperation之间有依赖关系,也可以设置,具体可以参考API文档。 


(2)非并发执行

-(void)main

只需要重载这个main方法就可以了。

dispatch_async(dispatch_queue_t queue,dispatch_block_t block);

async表明异步运行,block代表的是你要做的事情,queue则是你把任务交给谁来处理了.

之所以程序中会用到多线程是因为程序往往会需要读取数据,然后更新UI.为了良好的用户体验,读取数据的操作会倾向于在后台运行,这样以避免阻塞主线程.GCD里就有三种queue来处理。

GCD

  1. Main queue:

  2. 顾名思义,运行在主线程,由dispatch_get_main_queue获得.和ui相关的就要使用MainQueue.

  3. 2.Serial quque(private dispatch queue)

  4. 每次运行一个任务,可以添加多个,执行次序FIFO. 通常是指程序员生成的.

  5. 3. Concurrent queue(globaldispatch queue):

  6. 可以同时运行多个任务,每个任务的启动时间是按照加入queue的顺序,结束的顺序依赖各自的任务.使用dispatch_get_global_queue获得.

  7. 所以我们可以大致了解使用GCD的框架: