iOS学习笔记-119.多线程18——NSOperationQueue自定义NSOperation执行一个操作的取消

多线程18——NSOperationQueue自定义NSOperation执行一个操作的取消

一、场景说明

我们创建自定义了一个 NSOperation 它里面执行多个耗时任务,根据我们前面的知识,只有这个操作执行完了,我们才能取消。现在我希望是有三个耗时的任务,任务1执行完了能够取消,任务2执行完了也能取消。那么我们需要怎么实现呢???

其实很简单啦。我们只需要在任务1执行完了判断一下,当前的任务是否已经取消了,取消了那么返回,没有取消那么继续。


二、代码示例

2.1 QWMOperation2.m

//
//  QWMOperation2.m
//  03_UIview85多线程_NSOperation
//
//  Created by 杞文明 on 17/9/4.
//  Copyright © 2017年 杞文明. All rights reserved.
//

#import "QWMOperation2.h"

@implementation QWMOperation2

-(void)main{
    //3个耗时操作
    //耗时任务 1
    for (NSInteger i = 0; i<1000;i++ ) {
        NSLog(@"download1---%zd--%@",i,[NSThread currentThread]);
    }

    //苹果官方的建议:每执行完一小段耗时操作的时候判断当前操作时候被取消
    if(self.isCancelled)return;

    NSLog(@"+++++++++++++++");

    //耗时任务 2
    for (NSInteger i = 0; i<1000;i++ ) {
        NSLog(@"download2---%zd--%@",i,[NSThread currentThread]);
    }

    if(self.isCancelled)return;
    NSLog(@"+++++++++++++++");

    //耗时任务 3
    for (NSInteger i = 0; i<1000;i++ ) {
        NSLog(@"download3---%zd--%@",i,[NSThread currentThread]);
    }

}

@end

2.2 代码示例


- (IBAction)startClick:(id)sender {
    if(_queue==nil){
        _queue = [[NSOperationQueue alloc]init];
        _queue.maxConcurrentOperationCount = 1;
    }
    [self test2];
}

- (IBAction)cancelClick:(id)sender {
    //取消,不可以恢复
    //该方法内部调用了所有操作的cancel方法
    [self.queue cancelAllOperations];
}

-(void)test2{
    QWMOperation2 *op = [[QWMOperation2 alloc]init];
    [self.queue addOperation:op];
}

三、运行结果

[26503:132215] download1---0--<NSThread: 0x608000071880>{number = 5, name = (null)}
[26503:132215] download1---1--<NSThread: 0x608000071880>{number = 5, name = (null)}
[26503:132215] download1---2--<NSThread: 0x608000071880>{number = 5, name = (null)}
......
[26503:132215] download1---997--<NSThread: 0x608000071880>{number = 5, name = (null)}
[26503:132215] download1---998--<NSThread: 0x608000071880>{number = 5, name = (null)}
[26503:132215] download1---999--<NSThread: 0x608000071880>{number = 5, name = (null)}
[26503:132215] +++++++++++++++
[26503:132215] download2---0--<NSThread: 0x608000071880>{number = 5, name = (null)}
[26503:132215] download2---1--<NSThread: 0x608000071880>{number = 5, name = (null)}
[26503:132215] download2---2--<NSThread: 0x608000071880>{number = 5, name = (null)}
......
[26503:132215] download2---997--<NSThread: 0x608000071880>{number = 5, name = (null)}
[26503:132215] download2---998--<NSThread: 0x608000071880>{number = 5, name = (null)}
[26503:132215] download2---999--<NSThread: 0x608000071880>{number = 5, name = (null)}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值