您的位置:首页 > 运维架构

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

2016-01-09 15:02 417 查看
//

//  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 = [[super
alloc] 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 {

    [super
viewDidLoad];

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

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

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

    [op1 setCompletionBlock:^{

        NSLog(@"op1 finish");

    }];

    [op2 setCompletionBlock:^{

        NSLog(@"op2 finish");

    }];

    self.queue = [[NSOperationQueue
alloc]
init];

    [self.queue
addOperation:op1];

    [self.queue
addOperation: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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  多线程 NSOperation ios