ios - Implement an asynchronously NSOperation -
i studying nsoperation object. according app document (listing 2-5), can implement asynchronously nsoperation. part of start part below:
- (void)start { // check cancellation before launching task. if ([self iscancelled]) { // must move operation finished state if canceled. [self willchangevalueforkey:@"isfinished"]; finished = yes; [self didchangevalueforkey:@"isfinished"]; return; } // if operation not canceled, begin executing task. [self willchangevalueforkey:@"isexecuting"]; [nsthread detachnewthreadselector:@selector(main) totarget:self withobject:nil]; executing = yes; [self didchangevalueforkey:@"isexecuting"]; }
i find out new thread assigned run main function:
[nsthread detachnewthreadselector:@selector(main) totarget:self withobject:nil];
so, seems nsoperation did nothing concurrent execution. asynchrony achieve create new thread. why need nsoperation?
you may use concurrent nsoperation
execute asynchronous task. should emphasize on fact, asynchronous task's main work execute on different thread start
method has been invoked.
so, why useful?
wrapping asynchronous task concurrent nsoperation
lets leverage nsoperationqueue
, furthermore enables setup dependencies between other operations.
for example, enqueuing operations nsoperationqueue
lets define how many operations execute in parallel. can cancel whole queue, is, operations have been enqueued.
an nsoperationqueue
useful associate resources - example, 1 queue executes cpu bound asynchronous tasks, executes io bound task, , yet executes tasks related core data, , force. each queue can define maximum number of concurrent operations.
with dependencies can achieve composition. means example, can define operation c executes after operation , b have been finished. composition can solve more complex asynchronous problems.
that's it, imho.
i mention, using nsoperations cumbersome, clunky , verbose, requires lot of boilerplate code , subclasses , such. there better alternatives require third party libraries, though.
Comments
Post a Comment