1. 含义:NSOperation,NSOperationQueue是什么。

The NSOperation class is an abstract class you use to encapsulate the code and data associated with a single task.NSOperation是一个你需要将代码和数据放在一个单任务中执行的抽象类。

The NSOperationQueue class regulates the execution of a set of NSOperation objects.NSOperationQueue是用来管理多个NSOperation对象的一个类。

2.使用方法

使用 NSOperation的方式有两种,

  1. 一种是用定义好的两个子类:

NSInvocationOperation 和 NSBlockOperation。

@interface ViewController ()  

@end  

@implementation ViewController  

- (void)viewDidLoad
{
[super viewDidLoad];
NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self
selector:@selector(downloadImage:)
object:kURL]; NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[queue addOperation:operation];
// Do any additional setup after loading the view, typically from a nib.
} -(void)downloadImage:(NSString *)url{
NSLog(@"url:%@", url);
NSURL *nsUrl = [NSURL URLWithString:url];
NSData *data = [[NSData alloc]initWithContentsOfURL:nsUrl];
UIImage * image = [[UIImage alloc]initWithData:data];
[self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];
}
-(void)updateUI:(UIImage*) image{
self.imageView.image = image;
}

2.另一种则是继承NSOperation,重写NSOperation的main方法

编写一个NSOperation的子类,只需实现main方法。这里非常类似Java的Thread,你可以继承它,并覆盖run方法,在该方法里面写入需要执行的代码。这里的main方法和run方法作用是相似的。

@interface MyTask : NSOperation {
int operationId;
} @property int operationId; @end

这里的operationId属性不是必须的,是我想在后面标识区分多个Task的标识位。

@implementation MyTask

@synthesize operationId;

- (void)main{
NSLog(@"task %i run … ",operationId);
[NSThread sleepForTimeInterval:];
NSLog(@"task %i is finished. ",operationId);
} @end

这里模拟了一个耗时10秒钟的操作。

-- ::14.622 MultiThreadTest[:] task  run …
-- ::24.623 MultiThreadTest[:] task is finished.

可以向操作队列(NSOperationQueue)增加多个操作,比如这样:

下面需要把Task加入到队列中:

- (void)viewDidLoad {
[super viewDidLoad];
queue=[[NSOperationQueue alloc] init]; int index=;
MyTask *task=[[[MyTask alloc] init] autorelease];
task.operationId=index++; [queue addOperation:task];

我直接找了个Controller的方法写上了。运行结果是,界面出现了,而task还未执行完,说明是多线程的。10秒钟后,日志打印完毕,类似这样:

- (void)viewDidLoad {
[super viewDidLoad];
queue=[[NSOperationQueue alloc] init]; int index=;
MyTask *task=[[[MyTask alloc] init] autorelease];
task.operationId=index++;
[queue addOperation:task]; task=[[[MyTask alloc] init] autorelease];
task.operationId=index++; [queue addOperation:task];
}

那么打印出的内容是不定的,有可能是这样:

-- ::48.087 MultiThreadTest[:] task  run …
-- ::48.087 MultiThreadTest[:] task run …
-- ::58.122 MultiThreadTest[:] task is finished.
-- ::58.122 MultiThreadTest[:] task is finished.

甚至有可能是这样:

-- ::24.686 MultiThreadTest[:1b03] task  run …
-- ::24.685 MultiThreadTest[:] task run …
-- ::34.708 MultiThreadTest[:1b03] task is finished.
-- ::34.708 MultiThreadTest[:] task is finished.

因为两个操作提交的时间间隔很近,线程池中的线程,谁先启动是不定的。

那么,如果需要严格意义的顺序执行,怎么办呢?

处理操作之间的依赖关系

如果操作直接有依赖关系,比如第二个操作必须等第一个操作结束后再执行,需要这样写:

queue=[[NSOperationQueue alloc] init];

int index=;
MyTask *task=[[[MyTask alloc] init] autorelease];
task.operationId=index++; [queue addOperation:task]; task=[[[MyTask alloc] init] autorelease];
task.operationId=index++; if ([[queue operations] count]>) {
MyTask *theBeforeTask=[[queue operations] lastObject];
[task addDependency:theBeforeTask];
} [queue addOperation:task];

这样,即使是多线程情况下,可以看到操作是严格按照先后次序执行的。

控制线程池中的线程数

可以通过类似下面的代码:

[queue setMaxConcurrentOperationCount:];

来设置线程池中的线程数,也就是并发操作数。默认情况下是-1,也就是没有限制,同时运行队列中的全部操作。

IOS多线程(NSOperation,NSOperationQueue)的更多相关文章

  1. iOS 多线程 NSOperation、NSOperationQueue

    1. NSOperation.NSOperationQueue 简介 NSOperation.NSOperationQueue 是苹果提供给我们的一套多线程解决方案.实际上 NSOperation.N ...

  2. iOS多线程 NSOperation的用法

    上一篇写了 GCD 的使用,接下来就了解一下 NSOperation ,NSOperation是苹果对 GCD 的 OC 版的一个封装,但是相对于GCD来说可控性更强,并且可以加入操作依赖. NSOp ...

  3. iOS多线程--NSOperation 浅显易懂

    NSOperation是基于GCD的一套多线程实现方案,和GCD一样,线程的生命周期是由系统来自动管理的,不用像NSThread和Pthread一样让程序员手动管理.相对于GCD来说,它更加地面向对象 ...

  4. iOS多线程--NSOperation

    NSOperation是基于GCD的一套多线程实现方案,和GCD一样,线程的生命周期是由系统来自动管理的,不用像NSThread和Pthread一样让程序员手动管理.相对于GCD来说,它更加地面向对象 ...

  5. iOS多线程---NSOperation介绍和使用

    1.  NSOperation实现多线程编程,需要和NSOperationQueue一起使用. (1)先将要执行的操作封装到NSOperation中 (2)将NSOperation对象添加到NSOpe ...

  6. IOS 多线程 NSOperation GCD

    1.NSInvocationOperation NSInvocationOperation * op; NSOperationQueue * que = [[NSOperationQueuealloc ...

  7. iOS多线程---NSOperation的常用操作

    1.最大并发数: - (NSInteger)maxConcurrentOperationCount;- (void)setMaxConcurrentOperationCount:(NSInteger) ...

  8. iOS多线程编程

    废话不多说,直接上干货.先熟悉一下基本知识,然后讲一下常用的两种,NSOperation和GCD. 一.基础概念 进程: 狭义定义:进程是正在运行的程序的实例(an instance of a com ...

  9. [转] iOS多线程编程之NSOperation和NSOperationQueue的使用

    <iOS多线程编程之NSThread的使用> 介绍三种多线程编程和NSThread的使用,这篇介绍NSOperation的使用. 使用 NSOperation的方式有两种, 一种是用定义好 ...

  10. iOS多线程编程之NSOperation和NSOperationQueue的使用

    前一篇 <iOS多线程编程之NSThread的使用> 介绍三种多线程编程和NSThread的使用,这篇介绍NSOperation的使用. 使用 NSOperation的方式有两种, 一种是 ...

随机推荐

  1. 【HDU 2577】How to Type

    题意 (我做了这题才知道caps lock 锁定大小写后,按一下shift键可以输入相反的大小写.) 这题就是给你只有大小写字母的字符串,求最少多少次按键盘.最后caps lock 必须是关闭的. 分 ...

  2. rpm常用选项

    httpd-2.2.15-39.el6.centos.x86_64.rpmhttpd   -      2.2.15-    39.el6.centos.       x86_64 .rpm软件名称- ...

  3. session共享

    Nginx或者Squit反向代理到两台tomcat服务器 tomcat使用memcached tomcat连接memcached工具 cp session/*.jar /usr/local/tomca ...

  4. BZOJ1086 [SCOI2005]王室联邦

    Description “余”人国的国王想重新编制他的国家.他想把他的国家划分成若干个省,每个省都由他们王室联邦的一个成 员来管理.他的国家有n个城市,编号为1..n.一些城市之间有道路相连,任意两个 ...

  5. 安装最新版本的ReSharper导致原生全局搜索工具的消失问题

    经过检测,是由于启用了一个插件导致的,禁用即可,如下图:

  6. Codeforces 650C Table Compression

    传送门 time limit per test 4 seconds memory limit per test 256 megabytes input standard input output st ...

  7. pthread_kill

    别被名字吓到,pthread_kill可不是kill,而是向线程发送signal.还记得signal吗,大部分signal的默认动作是终止进程的运行,所以,我们才要用signal()去抓信号并加上处理 ...

  8. linux下IPTABLES配置详解(转)

    如果你的IPTABLES基础知识还不了解,建议先去看看.开始配置我们来配置一个filter表的防火墙.(1)查看本机关于IPTABLES的设置情况[ ~]# iptables -L -nChain I ...

  9. Android学习笔记03-搭建Win8下的Android开发环境

    一  配置环境变量 (绿色文字标出代码,路径换为自己的SDK路径) ANDROID_HOME =  C:\software\adt-bundle-windows-x86_64-20140702\sdk ...

  10. vagrant up时提示 Authentication failure. Retrying

    vagrant up时提示 Authentication failure. Retrying 如图,启动时就报这个错误,virtualbox启动正常 用vagrant的账号密码也可以登录 就是不能使用 ...