The previous section, "IOS nsoperation non-concurrent execution" has been described in nsoperation the system-provided subclasses nsblockoperation and nsinvocationoperation tasks of non-concurrent execution, and added to Nsoperationqueue for concurrent execution. This section implements the Nsoperation subclasses and executes concurrently. Nsoperation Non-concurrency subclass implementation, simply re-cover the main method, the task to be executed into the main method, in the main method to do the cancel judgment, the following example: @interface mynonconcurrentoperation: Nsoperation
@property (strong) ID myData;
-(ID) Initwithdata: (ID) data;
@end @implementation Mynonconcurrentoperation
-(ID) Initwithdata: (ID) data
{
if (self = [super init])
{
_mydata = data;
}
return self;
}
-(void) Main
{
@try {
BOOL isDone = NO;
while (![ Self iscancelled] &&!isdone) {
Do some work and set IsDone to YES when finished
}
}
@catch (...) {
Do not rethrow exceptions.
}
} @end the nsoperation concurrency subclass implementation, you must override the start, Isconcurrent, isexecuting, and isfinished four methods, and the main method is optional @interface myoperation: nsoperation {
BOOL executing;
BOOL finished;
}
-(void) completeoperation; @end
@implementation Myoperation
-(ID) init {
self = [super init];
if (self) {
executing = NO;
finished = NO;
}
return self;
}
-(BOOL) isconcurrent {
return YES;
}
-(BOOL) isexecuting {
return executing;
}
-(BOOL) isfinished {
return finished;
}
-(void) Start {
Always check for cancellation before launching the task.
if ([Self iscancelled])
{
Must move the operation to the finished state if it is canceled.
[Self willchangevalueforkey:@ "isfinished"];
finished = YES;
[Self didchangevalueforkey:@ "isfinished"];
Return
}
If The operation is not canceled, begin executing the task.
[Self willchangevalueforkey:@ "isexecuting"];
[Nsthread Detachnewthreadselector: @selector (Main) totarget:self Withobject:nil];
executing = YES;
[Self didchangevalueforkey:@ "isexecuting"];
}
-(void) Main {
@try {
Do the main work of the operation here.
[Self completeoperation];
}
@catch (...) {
Do not rethrow exceptions.
}
}
-(void) Completeoperation {
[Self willchangevalueforkey:@ "isfinished"];
[Self willchangevalueforkey:@ "isexecuting"];
executing = NO;
finished = YES;
[Self didchangevalueforkey:@ "isexecuting"];
[Self didchangevalueforkey:@ "isfinished"];
The Nsoperation property adds the KVO mechanism, and when we override the property's Getter method, it returns according to the state we specify, so the KVO notification is initiated when the state changes, notifying the object that listens to the secondary property. The Start method uses Nsthread to open a new thread to implement concurrent execution.
IOS nsoperation subclass Implementation and concurrency execution