//
// 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