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

来源:互联网 发布:罗马全面战争火攻算法 编辑:程序博客网 时间:2024/06/06 07:16

  • 多线程18NSOperationQueue自定义NSOperation执行一个操作的取消
    • 一场景说明
    • 二代码示例
      • 1 QWMOperation2m
      • 2 代码示例
    • 三运行结果

多线程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
原创粉丝点击