NSInvovationOperation Object
NSInvovationOperation是NSOperation的一个子类,可以通过target,selector和object初始化,特别如果你要根据一个object执行一些动态的操作。
- (NSOperation *)taskWithData:(id)data {
return [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(myTaskMethod:) object:data];
}
- (void)myTaskMethod:(id)data {
NSLog(@"%@", data);
}
NSBlockOperation
NSBlockOperation可以通过一个Block初始化,但是Block没有参数和返回值
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
}];
Defining a Custom Operation Object
自定义一个Operation,最起码要实现的一些方法
* 一些实现过程中指定要的方法
* 实现main方法
例如一些自定义的方法只有有下面的几种:
* 一些在main方法中执行需要的方法
* setter getter方法,设置获取数据(OC)
* 实现NSCoding,让你的Operation可以archive and unarchive
@interface MyNonConcurrentOperation : NSOperation
@property (nonatomic, strong) id data;
- (instancetype)initWithData:(id)data;
@end
@implementation MyNonConcurrentOperation
- (instancetype)initWithData:(id)data {
self = [super init];
if (!self) return nil;
_data = data;
return self;
}
- (void)main {
}
@end
Responding to Cancellation Events
Operation可以通过isCancelled来取消操作。当天return YES的时候就可以取消了。主要在下面这几种情况下添加取消
* 在执行任务之前
* 在循环操作中
* 在容易退出的地方
Configuring Operations for Concurrent Execution
自定义一个Concurrent Opertaion,要做以下几步
* override start方法,重写它,替换默认的实现,可以通过start方法手动执行它,也可以防止queue中,不用调用super的方法。
* main方法,这个方法是可选实现的,因为可以把实现写在start方法中,写一个的好出是,可以分开逻辑。
* isExecuting,isFinish,Concurrent Opertaion要维护自己的状态,通过KVO进行通知,如果状态改变。
* isAsynchronous,返回YES,或NO,标识是不是Asynchronous,以前废除那个就不说了。
//
// MyOperation.m
// fsafsf
//
// Created by EvilSylvanas on 6/4/16.
// Copyright © 2016 EvilSylvanas. All rights reserved.
//
#import "MyOperation.h"
typedef NS_ENUM(NSInteger, StateType) {
StateTypeExecuting,
StateTypeFinished
};
@interface MyOperation()
@property (nonatomic, assign) StateType state;
@end
@implementation MyOperation
- (BOOL)isAsynchronous {
return YES;
}
- (BOOL)isExecuting {
return self.state == StateTypeExecuting;
}
- (BOOL)isFinished {
return self.state == StateTypeFinished;
}
- (void)start {
if ([self isCancelled]) {
[self willChangeValueForKey:@"isFinished"];
self.state = StateTypeFinished;
[self didChangeValueForKey:@"isFinished"];
return;
}
[self main];
[self willChangeValueForKey:@"isExecuting"];
self.state = StateTypeFinished;
[self didChangeValueForKey:@"isExecuting"];
}
- (void)main {
}
- (void)completeOperation {
[self willChangeValueForKey:@"isFinished"];
[self willChangeValueForKey:@"isExecuting"];
self.state = StateTypeFinished;
[self didChangeValueForKey:@"isExecuting"];
[self didChangeValueForKey:@"isFinished"];
}
@end