继承NSOperation类完成能被cancel的耗时操作

来源:互联网 发布:office电脑版办公软件 编辑:程序博客网 时间:2024/06/13 04:00

//

//  MyOperation.h

//  NSOperation

//

//  Created by zmx on 16/1/8.

//  Copyright © 2016 zmx. All rights reserved.

//


#import <Foundation/Foundation.h>


@interface MyOperation : NSOperation


+ (instancetype)operationWithOpname:(NSString *)opname;


@end



//

//  MyOperation.m

//  NSOperation

//

//  Created by zmx on 16/1/8.

//  Copyright © 2016 zmx. All rights reserved.

//


#import "MyOperation.h"


@interface MyOperation ()


@property (nonatomic,copy) NSString *opname;


@end


@implementation MyOperation


+ (instancetype)operationWithOpname:(NSString *)opname {

    MyOperation *operation = [[superalloc] init];

    operation.opname = opname;

    return operation;

}


- (void)main {

    for (int i =0; i < 1000; i++) {

        if (self.isCancelled) {

            return;

        }

        NSLog(@"%@--%d",self.opname, i);

    }

}


@end



//

//  ViewController.m

//  NSOperation

//

//  Created by zmx on 16/1/8.

//  Copyright © 2016 zmx. All rights reserved.

//


#import "ViewController.h"

#import "MyOperation.h"


@interface ViewController ()


@property (nonatomic,strong) NSOperationQueue *queue;


@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    MyOperation *op1 = [MyOperationoperationWithOpname:@"op1"];

    MyOperation *op2 = [MyOperationoperationWithOpname:@"op2"];

    [op1 setCompletionBlock:^{

        NSLog(@"op1 finish");

    }];

    [op2 setCompletionBlock:^{

        NSLog(@"op2 finish");

    }];

    self.queue = [[NSOperationQueuealloc] init];

    [self.queueaddOperation:op1];

    [self.queueaddOperation:op2];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)),dispatch_get_main_queue(), ^{

        [op2 cancel];

    });

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)),dispatch_get_main_queue(), ^{

        [op1 cancel];

    });

}


@end

0 0
原创粉丝点击