iOS多线程(三):NSOperationQueue 的使用

1 简单使用 NSOperationQueue

上一篇文章中看到使用自定义NSOperation来实现多线程,写法有些复杂,但其实,使用NSOperationQueue来实现多线程非常简单

- (void)viewDidLoad {
    [super viewDidLoad];
    // 创建3个 NSInvocationOperation 操作
    NSOperationQueue *opQueue = [NSOperationQueue new];
    for (NSUInteger i = 0; i < 3; i++) {
        // 可以传递一个 NSObject 给operation的操作方法
        NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Operation_%lu", i] forKey:@"key"];
        NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(operationSelector:) object:dict];
        [opQueue addOperation:op];
    }
}
    
// NSInvocationOperation 操作执行的方法
- (void)operationSelector:(NSDictionary *)dict
{
    // 接收传进来的dict
    NSLog(@"dictValue = %@", [dict valueForKey:@"key"]);
    sleep(10);  // 加个睡眠模仿耗时操作
    NSLog(@"currentThread = %@", [NSThread currentThread]);
    NSLog(@"mainThread    = %@", [NSThread mainThread]);
}

控制台输出结果为:

2016-02-25 16:58:18.282 test[57194:18487531] dictValue = Operation_0
2016-02-25 16:58:18.282 test[57194:18487530] dictValue = Operation_1
2016-02-25 16:58:18.282 test[57194:18487533] dictValue = Operation_2
2016-02-25 16:58:28.283 test[57194:18487530] currentThread = <NSThread: 0x7fbf40435bb0>{number = 2, name = (null)}
2016-02-25 16:58:28.284 test[57194:18487531] currentThread = <NSThread: 0x7fbf4050f2a0>{number = 3, name = (null)}
2016-02-25 16:58:28.284 test[57194:18487533] currentThread = <NSThread: 0x7fbf4290f560>{number = 4, name = (null)}
2016-02-25 16:58:28.284 test[57194:18487530] mainThread    = <NSThread: 0x7fbf405058c0>{number = 1, name = (null)}
2016-02-25 16:58:28.284 test[57194:18487531] mainThread    = <NSThread: 0x7fbf405058c0>{number = 1, name = (null)}
2016-02-25 16:58:28.284 test[57194:18487533] mainThread    = <NSThread: 0x7fbf405058c0>{number = 1, name = (null)}

可以看出来这三个操作是并发执行的,而且都不在主线程中执行。

2 NSOperationQueue 的其他属性

添加操作有3个方法:

// 直接添加一个 NSOperation 操作,并且加入并发队列,只要当前队列允许,就会立刻执行。
- (void)addOperation:(NSOperation *)op;
// 添加一组操作,如果 waitUntilFinished 为 NO,则必须在当前队列中的所有操作都执行完了,才会执行这组操作,否则立刻执行。
- (void)addOperations:(NSArray<NSOperation *> *)ops waitUntilFinished:(BOOL)wait NS_AVAILABLE(10_6, 4_0);
// 直接在这里写一个block,block中的操作加入并发队列,并且只要当前队列允许执行,就会立刻执行。
- (void)addOperationWithBlock:(void (^)(void))block NS_AVAILABLE(10_6, 4_0);

接下来看其他的属性

// 返回当前队列中的所有操作NSOperation
@property (readonly, copy) NSArray<__kindof NSOperation *> *operations;
// 返回当前队列中的操作数量,对应 operations.count
@property (readonly) NSUInteger operationCount NS_AVAILABLE(10_6, 4_0);
// 可读写的属性,当设备性能不足或根据需求要限制并行的操作数量时,可以设置这个值。
// 设置了这个值之后,队列中并发执行的操作数量不会大于这个值。超出这个值在排队中的操作会处于休眠状态。
// 默认值为 NSOperationQueueDefaultMaxConcurrentOperationCount = -1
@property NSInteger maxConcurrentOperationCount;
// 可以给队列指定一个名字用来做标识
@property (nullable, copy) NSString *name NS_AVAILABLE(10_6, 4_0);
// 给队列指定一个优先级,默认为 NSQualityOfServiceDefault = -1
@property NSQualityOfService qualityOfService NS_AVAILABLE(10_10, 8_0);
// ??? 这个不是太理解
@property (nullable, assign /* actually retain */) dispatch_queue_t underlyingQueue NS_AVAILABLE(10_10, 8_0);
// 取消队列中的所有操作。其实就是调用 operations 中每个操作的`cancel`方法才取消操作。
// 但是,在前面的文章中说过,调用`cancel`方法并不会终止操作,而是设置`cancelled`属性为 YES,
// 这就需要自己在操作中分节点去判断`cancelled`属性了,在适当的时机结束操作。
- (void)cancelAllOperations;
// 调用这个方法时,会判断 NSOperationQueue 中的操作是否全部执行完,如果没有,则调用者所在的线程会在调用处等待。
// 直到 NSOperationQueue 中的所有操作执行完成,当前线程才继续执行。如果 NSOperationQueue 为空,则该方法立刻返回。
- (void)waitUntilAllOperationsAreFinished;
// 取得调用者的当前线程中的 NSOperationQueue 操作队列
+ (nullable NSOperationQueue *)currentQueue NS_AVAILABLE(10_6, 4_0);
// 取得主线程中的 
+ (NSOperationQueue *)mainQueue NS_AVAILABLE(10_6, 4_0);
@property (getter=isSuspended) BOOL suspended;

这个值很有意思,从字面意思理解是暂停队列,但是怎么个暂停呢?从官方文档上看

**Discussion**
When the value of this property is NO, the queue actively starts operations that are in the queue and ready to execute. Setting this property to YES prevents the queue from starting any queued operations, but already executing operations continue to execute. You may continue to add operations to a queue that is suspended but those operations are not scheduled for execution until you change this property to NO.

Operations are removed from the queue only when they finish executing. However, in order to finish executing, an operation must first be started. Because a suspended queue does not start any new operations, it does not remove any operations (including cancelled operations) that are currently queued and not executing.

You may monitor changes to the value of this property using key-value observing. Configure an observer to monitor the suspended key path of the operation queue.

The default value of this property is NO.

大概翻译一下,如果这个值设置为 NO,那说明这个队列已经准备好了可以执行了。如果这个值设置为 YES,那么已经添加到队列中的操作还是可以执行了,而后面继续添加进队列中的操作才处于暂停状态,直到你再次将这个值设置为 NO 时,后面加入的操作才会继续执行。这个属性的默认值是 NO。

来看一下使用的方法例子:

- (void)viewDidLoad {
    [super viewDidLoad];
    // 创建3个 NSInvocationOperation 操作
    _opQueue = [NSOperationQueue new];
    for (NSUInteger i = 0; i < 3; i++) {
        // 可以传递一个 NSObject 给operation的操作方法
        NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Operation_%lu", i] forKey:@"key"];
        NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(operationSelector:) object:dict];
        [_opQueue addOperation:op];
    }
    // 这里设置为 YES
    _opQueue.suspended = YES;
    // 然后再添加一个操作,序号为 9
    NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"Operation_%d", 9] forKey:@"key"];
    NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(operationSelector:) object:dict];
    [_opQueue addOperation:op];
}
// NSInvocationOperation 操作执行的方法
- (void)operationSelector:(NSDictionary *)dict
{
    // 接收传进来的dict
    NSLog(@"dictValue = %@", [dict valueForKey:@"key"]);
    sleep(10);  // 加个睡眠模仿耗时操作
    NSLog(@"currentThread = %@", [NSThread currentThread]);
    NSLog(@"mainThread    = %@", [NSThread mainThread]);
    // 执行完其中一个操作之后把 suspended 改为 NO。
    _opQueue.suspended = NO;
}
2016-02-25 17:22:07.546 test[57547:18605364] dictValue = Operation_2
2016-02-25 17:22:07.546 test[57547:18605360] dictValue = Operation_0
2016-02-25 17:22:07.546 test[57547:18605361] dictValue = Operation_1
2016-02-25 17:22:10.547 test[57547:18605361] currentThread = <NSThread: 0x7ff598d07b00>{number = 3, name = (null)}
2016-02-25 17:22:10.547 test[57547:18605364] currentThread = <NSThread: 0x7ff59a9784f0>{number = 2, name = (null)}
2016-02-25 17:22:10.547 test[57547:18605360] currentThread = <NSThread: 0x7ff59aa05100>{number = 4, name = (null)}
2016-02-25 17:22:10.547 test[57547:18605364] mainThread    = <NSThread: 0x7ff598c08770>{number = 1, name = (null)}
2016-02-25 17:22:10.547 test[57547:18605360] mainThread    = <NSThread: 0x7ff598c08770>{number = 1, name = (null)}
2016-02-25 17:22:10.547 test[57547:18605361] mainThread    = <NSThread: 0x7ff598c08770>{number = 1, name = (null)}
2016-02-25 17:22:10.547 test[57547:18605513] dictValue = Operation_9
2016-02-25 17:22:13.620 test[57547:18605513] currentThread = <NSThread: 0x7ff598c08ce0>{number = 5, name = (null)}
2016-02-25 17:22:13.620 test[57547:18605513] mainThread    = <NSThread: 0x7ff598c08770>{number = 1, name = (null)}

可以看出来,操作9是在suspended改为 NO 之后才开始执行的。

最后:以上很多属性都支持 KVO ,可以通过监听某个值的变化来做不同的操作,这里就不赘述了。

3 总结

NSOperationQueue为我们提供了非常简便的使用多线程的方法,如果需要使用NSOperation,则更多建议使用NSOperationQueue而不是自定义NSOperation

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容