这篇文章写得非常不错,基础用法都涉及到了,我把文章提到的例子都写到了demo里面,

原文地址: iOS多线程--彻底学会多线程之『NSOperation』

demo下载:https://github.com/wangdachui/multithreading.git

1. NSOperation简介

NSOperation是苹果提供给我们的一套多线程解决方案。实际上NSOperation是基于GCD更高一层的封装,但是比GCD更简单易用、代码可读性也更高。

NSOperation需要配合NSOperationQueue来实现多线程。因为默认情况下,NSOperation单独使用时系统同步执行操作,并没有开辟新线程的能力,只有配合NSOperationQueue才能实现异步执行。

因为NSOperation是基于GCD的,那么使用起来也和GCD差不多,其中,NSOperation相当于GCD中的任务,而NSOperationQueue则相当于GCD中的队列。NSOperation实现多线程的使用步骤分为三步:

  1. 创建任务:先将需要执行的操作封装到一个NSOperation对象中。
  2. 创建队列:创建NSOperationQueue对象。
  3. 将任务加入到队列中:然后将NSOperation对象添加到NSOperationQueue中。

之后呢,系统就会自动将NSOperationQueue中的NSOperation取出来,在新线程中执行操作。

下面我们来学习下NSOperation和NSOperationQueue的基本使用。

2.NSOperation和NSOperationQueue的基本使用

1. 创建任务

NSOperation是个抽象类,并不能封装任务。我们只有使用它的子类来封装任务。我们有三种方式来封装任务。

  1. 使用子类NSInvocationOperation
  2. 使用子类NSBlockOperation
  3. 定义继承自NSOperation的子类,通过实现内部相应的方法来封装任务。

在不使用NSOperationQueue,单独使用NSOperation的情况下系统同步执行操作,下面我们学习以下任务的三种创建方式。

1. 使用子类- NSInvocationOperation:

// 1.创建NSInvocationOperation对象
NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil]; // 2.调用start方法开始执行操作
[op start]; - (void)run
{
NSLog(@"------%@", [NSThread currentThread]);
}

输出结果:
2016-09-05 14:29:58.483 NSOperation[15834:2384555] ------<NSThread: 0x7fa3e2e05410>{number = 1, name = main}

从中可以看到,在没有使用NSOperationQueue、单独使用NSInvocationOperation的情况下,NSInvocationOperation在主线程执行操作,并没有开启新线程。

下边再来看看NSBlockOperation。

2. 使用子类- NSBlockOperation

NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
// 在主线程
NSLog(@"------%@", [NSThread currentThread]);
}]; [op start];

输出结果:
2016-09-05 14:33:15.268 NSOperation[15884:2387780] ------<NSThread: 0x7fb2196012c0>{number = 1, name = main}

我们同样可以看到,在没有使用NSOperationQueue、单独使用NSBlockOperation的情况下,NSBlockOperation也是在主线程执行操作,并没有开启新线程。

但是,NSBlockOperation还提供了一个方法addExecutionBlock:,通过addExecutionBlock:就可以为NSBlockOperation添加额外的操作,这些额外的操作就会在其他线程并发执行。

- (void)blockOperation
{
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
// 在主线程
NSLog(@"1------%@", [NSThread currentThread]);
}]; // 添加额外的任务(在子线程执行)
[op addExecutionBlock:^{
NSLog(@"2------%@", [NSThread currentThread]);
}];
[op addExecutionBlock:^{
NSLog(@"3------%@", [NSThread currentThread]);
}];
[op addExecutionBlock:^{
NSLog(@"4------%@", [NSThread currentThread]);
}]; [op start];
}

输出结果:
2016-09-05 14:36:59.353 NSOperation[15896:2390616] 1------<NSThread: 0x7ff633f03be0>{number = 1, name = main}
2016-09-05 14:36:59.354 NSOperation[15896:2390825] 2------<NSThread: 0x7ff633e24600>{number = 2, name = (null)}
2016-09-05 14:36:59.354 NSOperation[15896:2390657] 3------<NSThread: 0x7ff633c411e0>{number = 3, name = (null)}
2016-09-05 14:36:59.354 NSOperation[15896:2390656] 4------<NSThread: 0x7ff633f1d3e0>{number = 4, name = (null)}

可以看出,blockOperationWithBlock:方法中的操作是在主线程中执行的,而addExecutionBlock:方法中的操作是在其他线程中执行的。

3. 定义继承自NSOperation的子类

先定义一个继承自NSOperation的子类,重写main方法
YSCOperation.h

#import <Foundation/Foundation.h>

@interface YSCOperation : NSOperation

@end

YSCOperation.m

#import "YSCOperation.h"

@implementation YSCOperation
/**
* 需要执行的任务
*/ - (void)main
{
for (int i = 0; i < 2; ++i) {
NSLog(@"1-----%@",[NSThread currentThread]);
}
} @end

然后使用的时候导入头文件YSCOperation.h

// 创建YSCOperation
YSCOperation *op1 = [[YSCOperation alloc] init]; [op1 start];

输出结果:
2016-09-05 18:15:59.674 NSOperation[16566:2501606] 1-----<NSThread: 0x7f8030d05150>{number = 1, name = main}
2016-09-05 18:15:59.675 NSOperation[16566:2501606] 1-----<NSThread: 0x7f8030d05150>{number = 1, name = main}

可以看出:在没有使用NSOperationQueue、单独使用自定义子类的情况下,是在主线程执行操作,并没有开启新线程。

下边我们简单讲讲NSOperationQueue的创建。

2. 创建队列

和GCD中的并发队列、串行队列略有不同的是:NSOperationQueue一共有两种队列:主队列、其他队列。其中其他队列同时包含了串行、并发功能。下边是主队列、其他队列的基本创建方法和特点。

  • 主队列

    • 凡是添加到主队列中的任务(NSOperation),都会放到主线程中执行

      NSOperationQueue *queue = [NSOperationQueue mainQueue];
  • 其他队列(非主队列)
    • 添加到这种队列中的任务(NSOperation),就会自动放到子线程中执行
    • 同时包含了:串行、并发功能
      NSOperationQueue *queue = [[NSOperationQueue alloc] init];

3. 将任务加入到队列中

前边说了,NSOperation需要配合NSOperationQueue来实现多线程。
那么我们需要将创建好的任务加入到队列中去。总共有两种方法

  1. - (void)addOperation:(NSOperation *)op;

    • 需要先创建任务,再将创建好的任务加入到创建好的队列中去
- (void)addOperationToQueue
{
// 1.创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init]; // 2. 创建操作
// 创建NSInvocationOperation
NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil];
// 创建NSBlockOperation
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
for (int i = 0; i < 2; ++i) {
NSLog(@"1-----%@", [NSThread currentThread]);
}
}]; // 3. 添加操作到队列中:addOperation:
[queue addOperation:op1]; // [op1 start]
[queue addOperation:op2]; // [op2 start]
} - (void)run
{
for (int i = 0; i < 2; ++i) {
NSLog(@"2-----%@", [NSThread currentThread]);
}
}

输出结果:
2016-09-05 17:06:00.241 NSOperationQueue[16201:2452281] 1-----<NSThread: 0x7fe4824080e0>{number = 3, name = (null)}
2016-09-05 17:06:00.241 NSOperationQueue[16201:2452175] 2-----<NSThread: 0x7fe482404a50>{number = 2, name = (null)}
2016-09-05 17:06:00.242 NSOperationQueue[16201:2452175] 2-----<NSThread: 0x7fe482404a50>{number = 2, name = (null)}
2016-09-05 17:06:00.241 NSOperationQueue[16201:2452281] 1-----<NSThread: 0x7fe4824080e0>{number = 3, name = (null)}

可以看出:NSInvocationOperation和NSOperationQueue结合后能够开启新线程,进行并发执行NSBlockOperation和NSOperationQueue也能够开启新线程,进行并发执行。

  1. - (void)addOperationWithBlock:(void (^)(void))block;

    • 无需先创建任务,在block中添加任务,直接将任务block加入到队列中。
- (void)addOperationWithBlockToQueue
{
// 1. 创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init]; // 2. 添加操作到队列中:addOperationWithBlock:
[queue addOperationWithBlock:^{
for (int i = 0; i < 2; ++i) {
NSLog(@"-----%@", [NSThread currentThread]);
}
}];
}

输出结果:
2016-09-05 17:10:47.023 NSOperationQueue[16293:2457487] -----<NSThread: 0x7ffa6bc0e1e0>{number = 2, name = (null)}
2016-09-05 17:10:47.024 NSOperationQueue[16293:2457487] -----<NSThread: 0x7ffa6bc0e1e0>{number = 2, name = (null)}

可以看出addOperationWithBlock:和NSOperationQueue能够开启新线程,进行并发执行。

3. 控制串行执行和并行执行的关键

之前我们说过,NSOperationQueue创建的其他队列同时具有串行、并发功能,上边我们演示了并发功能,那么他的串行功能是如何实现的?

这里有个关键参数maxConcurrentOperationCount,叫做最大并发数

  • 最大并发数:maxConcurrentOperationCount

    • maxConcurrentOperationCount默认情况下为-1,表示不进行限制,默认为并发执行。
    • maxConcurrentOperationCount为1时,进行串行执行。
    • maxConcurrentOperationCount大于1时,进行并发执行,当然这个值不应超过系统限制,即使自己设置一个很大的值,系统也会自动调整。
- (void)opetationQueue
{
// 创建队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init]; // 设置最大并发操作数
// queue.maxConcurrentOperationCount = 2;
queue.maxConcurrentOperationCount = 1; // 就变成了串行队列 // 添加操作
[queue addOperationWithBlock:^{
NSLog(@"1-----%@", [NSThread currentThread]);
[NSThread sleepForTimeInterval:0.01];
}];
[queue addOperationWithBlock:^{
NSLog(@"2-----%@", [NSThread currentThread]);
[NSThread sleepForTimeInterval:0.01];
}];
[queue addOperationWithBlock:^{
NSLog(@"3-----%@", [NSThread currentThread]);
[NSThread sleepForTimeInterval:0.01];
}];
[queue addOperationWithBlock:^{
NSLog(@"4-----%@", [NSThread currentThread]);
[NSThread sleepForTimeInterval:0.01];
}];
[queue addOperationWithBlock:^{
NSLog(@"5-----%@", [NSThread currentThread]);
[NSThread sleepForTimeInterval:0.01];
}]; [queue addOperationWithBlock:^{
NSLog(@"6-----%@", [NSThread currentThread]);
[NSThread sleepForTimeInterval:0.01];
}];
}

最大并发数为1输出结果:
2016-09-05 17:21:54.124 NSOperationQueue[16320:2464630] 1-----<NSThread: 0x7fc892d0b3a0>{number = 2, name = (null)}
2016-09-05 17:21:54.136 NSOperationQueue[16320:2464631] 2-----<NSThread: 0x7fc892c0a7b0>{number = 3, name = (null)}
2016-09-05 17:21:54.148 NSOperationQueue[16320:2464630] 3-----<NSThread: 0x7fc892d0b3a0>{number = 2, name = (null)}
2016-09-05 17:21:54.160 NSOperationQueue[16320:2464631] 4-----<NSThread: 0x7fc892c0a7b0>{number = 3, name = (null)}
2016-09-05 17:21:54.171 NSOperationQueue[16320:2464631] 5-----<NSThread: 0x7fc892c0a7b0>{number = 3, name = (null)}
2016-09-05 17:21:54.184 NSOperationQueue[16320:2464630] 6-----<NSThread: 0x7fc892d0b3a0>{number = 2, name = (null)}

最大并发数为2输出结果:
2016-09-05 17:23:36.030 NSOperationQueue[16331:2466366] 2-----<NSThread: 0x7fd729f0f270>{number = 3, name = (null)}
2016-09-05 17:23:36.030 NSOperationQueue[16331:2466491] 1-----<NSThread: 0x7fd729f4e290>{number = 2, name = (null)}
2016-09-05 17:23:36.041 NSOperationQueue[16331:2466367] 3-----<NSThread: 0x7fd729d214e0>{number = 4, name = (null)}
2016-09-05 17:23:36.041 NSOperationQueue[16331:2466366] 4-----<NSThread: 0x7fd729f0f270>{number = 3, name = (null)}
2016-09-05 17:23:36.053 NSOperationQueue[16331:2466366] 6-----<NSThread: 0x7fd729f0f270>{number = 3, name = (null)}
2016-09-05 17:23:36.053 NSOperationQueue[16331:2466511] 5-----<NSThread: 0x7fd729e056c0>{number = 5, name = (null)}

可以看出:当最大并发数为1时,任务是按顺序串行执行的。当最大并发数为2时,任务是并发执行的。而且开启线程数量是由系统决定的,不需要我们来管理。这样看来,是不是比GCD还要简单了许多?

4. 操作依赖

NSOperation和NSOperationQueue最吸引人的地方是它能添加操作之间的依赖关系。比如说有A、B两个操作,其中A执行完操作,B才能执行操作,那么就需要让B依赖于A。具体如下:

- (void)addDependency
{
NSOperationQueue *queue = [[NSOperationQueue alloc] init]; NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"1-----%@", [NSThread currentThread]);
}];
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"2-----%@", [NSThread currentThread]);
}]; [op2 addDependency:op1]; // 让op2 依赖于 op1,则先执行op1,在执行op2 [queue addOperation:op1];
[queue addOperation:op2];
}

输出结果:
2016-09-05 17:51:28.811 操作依赖[16423:2484866] 1-----<NSThread: 0x7fc138e1e7c0>{number = 2, name = (null)}
2016-09-05 17:51:28.812 操作依赖[16423:2484866] 2-----<NSThread: 0x7fc138e1e7c0>{number = 2, name = (null)}

可以看到,无论运行几次,其结果都是op1先执行,op2后执行。

5. 一些其他方法

  • - (void)cancel; NSOperation提供的方法,可取消单个操作
  • - (void)cancelAllOperations; NSOperationQueue提供的方法,可以取消队列的所有操作
  • - (void)setSuspended:(BOOL)b; 可设置任务的暂停和恢复,YES代表暂停队列,NO代表恢复队列
  • - (BOOL)isSuspended; 判断暂停状态

  • 注意:

    • 这里的暂停和取消并不代表可以将当前的操作立即取消,而是当当前的操作执行完毕之后不再执行新的操作。
    • 暂停和取消的区别就在于:暂停操作之后还可以恢复操作,继续向下执行;而取消操作之后,所有的操作就清空了,无法再接着执行剩下的操作。

iOS多线程编程--NSOperation(转)的更多相关文章

  1. iOS多线程编程指南

    iOS多线程编程指南(拓展篇)(1) 一.Cocoa 在Cocoa上面使用多线程的指南包括以下这些: (1)不可改变的对象一般是线程安全的.一旦你创建了它们,你可以把这些对象在线程间安全的传递.另一方 ...

  2. iOS多线程编程原理及实践

    摘要:iOS开发中,开发者不仅要做好iOS的内存管理,而且如果你的iOS涉及多线程,那你也必须了解iOS编程中对多线程的限制,iOS主线程的堆栈大小为1M,其它线程均为512KB,且这个限制开发者是无 ...

  3. iOS多线程编程技术之NSThread、Cocoa NSOperation、GCD

    原文出处: 容芳志的博客 简介iOS有三种多线程编程的技术,分别是:(一)NSThread(二)Cocoa NSOperation(三)GCD(全称:Grand Central Dispatch) 这 ...

  4. iOS多线程编程Part 2/3 - NSOperation

    多线程编程Part 1介绍了NSThread以及NSRunLoop,这篇Blog介绍另一种并发编程技术:NSOPeration. NSOperation & NSOperationQueue ...

  5. IOS高级编程之三:IOS 多线程编程

    多线程的概念在各个操作系统上都会接触到,windows.Linux.mac os等等这些常用的操作系统,都支持多线程的概念. 当然ios中也不例外,但是线程的运行节点可能是我们平常不太注意的. 例如: ...

  6. iOS多线程编程

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

  7. iOS多线程编程(四)------ GCD(Grand Central Dispatch)

    一.简单介绍 是基于C语言开发的一套多线程开发机制.也是眼下苹果官方推荐的多线程开发方法.用起来也最简单.仅仅是它基于C语言开发,并不像NSOperation是面向对象的开发.而是全然面向过程的.假设 ...

  8. iOS多线程编程的知识梳理

    多线程编程也称之为并发编程,由于其作用大,有比较多的理论知识,因此在面试中也是受到面试官的青睐.在日常项目开发中,至少网络请求上是需要使用到多线程知识的,虽然使用第三方的框架比如AFNetworkin ...

  9. iOS多线程编程Part 1/3 - NSThread & Run Loop

    前言 多线程的价值无需赘述,对于App性能和用户体验都有着至关重要的意义,在iOS开发中,Apple提供了不同的技术支持多线程编程,除了跨平台的pthread之外,还提供了NSThread.NSOpe ...

随机推荐

  1. React-Native(二):React Native开发工具vs code配置

    从网上翻阅了一些开发react-native的开发工具时,发现其实可选的工具还是比较多的Sublime Text,WebStrom,Atom+Nuclide,vs code 等.因为我用.net生态环 ...

  2. 存图方式---邻接表&邻接矩阵&前向星

    基于vector存图 struct Edge { int u, v, w; Edge(){} Edge(int u, int v, int w):u(u), v(v), w(w){} }; vecto ...

  3. jacascript CSS样式的脚本化操作

    前言:这是笔者学习之后自己的理解与整理.如果有错误或者疑问的地方,请大家指正,我会持续更新! 引入CSS有3种方式:行间样式,内联样式和外部链接样式. 在实际工作中,我们使用 javascript 操 ...

  4. Java中List集合的三种遍历方式(全网最详)

    List集合在Java日常开发中是必不可少的,只要懂得运用各种各样的方法就可以大大提高我们开发的效率,适当活用各种方法才会使我们开发事半功倍. 我总结了三种List集合的遍历方式,下面一一来介绍. 首 ...

  5. libevent源码阅读笔记(一):libevent对epoll的封装

    title: libevent源码阅读笔记(一):libevent对epoll的封装 最近开始阅读网络库libevent的源码,阅读源码之前,大致看了张亮写的几篇博文(libevent源码深度剖析 h ...

  6. C#之FTP上传下载(一)

    搭建FTP服务器 最近要实现这样一个功能:FTP服务器的上传和下载,搜集了一些资料,在c播客上看到昵称为"傻丫头和科技"的作者写的一篇文章写得挺好,有的地方个人觉得不是很详细,自己 ...

  7. [LeetCode] Binary Number with Alternating Bits 有交替位的二进制数

    Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will a ...

  8. 在Unity3D中利用 RenderTexture 实现游戏内截图

    using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; publ ...

  9. Python---老王开枪

    class Person(object): """人类""" def __init__(self,name): super(Person,s ...

  10. [WC 2010]重建计划

    Description Input 第一行包含一个正整数N,表示X国的城市个数. 第二行包含两个正整数L和U,表示政策要求的第一期重建方案中修建道路数的上下限 接下来的N-1行描述重建小组的原有方案, ...