Nsoperation's role in conjunction with the use of nsoperation and nsoperationqueue can also achieve multi-threaded programming 1, nsoperation and nsoperationqueue multi-threaded implementation of the specific steps 2, The action that needs to be performed is encapsulated into a Nsoperation object 3, then the Nsoperation object is added to Nsoperationqueue 4, the system automatically takes nsoperation out of Nsoperationqueue 5, Putting the nsoperation encapsulated operation into a new thread executes nsoperation is an abstract class, does not have the ability to encapsulate operations, must use its subclass 1, using the Nsoperation subclass of the way there are 3 kinds of 2, NSInvocationOperation3, NSBlockOperation4, custom subclass inherit nsoperation, implement internal corresponding method The following is Demo@interface Czviewcontroller ()/** Nsoperation Operation Queue */@property (nonatomic, strong) Nsoperationqueue *queue; @end @implementation czviewcontroller// Add the action to the queue-(Nsoperationqueue *) queue{if (!_queue) _queue = [[Nsoperationqueue alloc] init]; return _queue;} -(void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event{[self opDemo6];} /** suspend Operation */-(ibaction) pause{//1. Determine if there is an action in the queue if (Self.queue.operationCount = = 0) {NSLog (@ "no action"); Return }//2. If it is not suspended (executing), it is necessary to suspend//only suspend the current queue that has not been scheduled (operations that are not scheduled to work on the thread) will be suspended if (!self.queue.issuspended) {NSLog (@ "paused"); [Self.queue Setsuspended:yes]; } else {NSLog (@ "has been paused"); }}/** continue Operation */-(ibaction) resume{//1. Determine if there is an action in the queue (Self.queue.operationCount = 0) {NSLog (@ "no action"); Return }//2. If there is a pending operation, it is necessary to continue (restore) if (self.queue.isSuspended) {NSLog (@ "continue"); [Self.queue Setsuspended:no]; } else {NSLog (@ "executing"); }} #pragma mark-nsoperation walkthrough/** The dependencies between Actions */-(void) opdemo6{nsblockoperation *op1 = [Nsblockoperation blockoperationwi thblock:^{NSLog (@ "Downloading books ... %@ ", [Nsthread CurrentThread]); }]; Nsblockoperation *OP2 = [nsblockoperation blockoperationwithblock:^{NSLog (@ "Extracting books ... %@ ", [Nsthread CurrentThread]); }]; Nsblockoperation *OP3 = [nsblockoperation blockoperationwithblock:^{NSLog (@ "Saving to disk ... %@ ", [Nsthread CurrentThread]); }]; Nsblockoperation *OP4 = [nsblockoperation blockoperationwithblock:^{NSLog (@ "Update the Bookshelf (UI), prompting the user to read ... %@ ", [Nsthread CurrentThread]); }]; //Specifies the "dependency" relationship between operations, the execution of one operation, which must wait for another operation to complete before it starts//dependencies are [OP2 ADDDEPENDENCY:OP1] that can be specified across queues; [Op3 ADDDEPENDENCY:OP2]; [OP4 ADDDEPENDENCY:OP3]; When adding dependencies, be careful not to see cyclic dependencies//[OP3 ADDDEPENDENCY:OP4]; [Self.queue ADDOPERATION:OP1]; [Self.queue ADDOPERATION:OP2]; [Self.queue ADDOPERATION:OP3]; Main queue Update UI [[Nsoperationqueue Mainqueue] ADDOPERATION:OP4];} /** maximum concurrency */-(void) opdemo5{//sets the maximum number of concurrent queues, the queue is the scenario that is responsible for the maximum number of concurrency for the scheduling operation: 1> users limit the number of threads when using 3G , saves power, saves traffic (save money) 2> users to increase the number of threads when using WiFi (LAN), improve the user experience maxconcurrentoperationcount if = = 1, similar to the serial queue async method */SE Lf.queue.maxConcurrentOperationCount = 1; for (int i = 0; i < i++) {[Self.queue addoperationwithblock:^{//Analog hibernation [Nsthread Slee PFORTIMEINTERVAL:1.0F]; NSLog (@ "Downloading%@%d", [Nsthread CurrentThread], i); }]; }}/** block operation, add execution block */-(void) opdemo4{//Instantiate block operation nsblockoperation *op = [[NsblockoperatIon Alloc] init]; Sets the maximum number of concurrent (operations), does not limit the execution block! Self.queue.maxConcurrentOperationCount = 2; Add execution block [op addexecutionblock:^{NSLog (@ "Download Book 1%@", [Nsthread CurrentThread]); }]; Continue adding block [op addexecutionblock:^{NSLog (@ "Download Book 2%@", [Nsthread CurrentThread]); }]; Continue adding block [op addexecutionblock:^{NSLog (@ "Download Book 3%@", [Nsthread CurrentThread]); }]; Continue adding block [op addexecutionblock:^{NSLog (@ "Download book 4%@", [Nsthread CurrentThread]); }]; Continue adding block [op addexecutionblock:^{NSLog (@ "Download Book 5%@", [Nsthread CurrentThread]); }]; The start operation, in the main thread execution//If the number of execution blocks exceeds 1, will automatically go to other threads Execution (async)//The number of specific open threads, the system decision//execution block scheduling and operation of the schedule very much like//[op start]; [Self.queue Addoperation:op];} /** Direct Add block operation */-(void) opdemo3{//The operation is immediately dispatched (executed) for (int i = 0; i < i++) {[Self.queue Addoper] as long as the action is added to the queue ationwithblock:^{NSLog (@ "Download start%@-%@", [Nsthread CurrentThread], @ (i)); }]; } //Add an action to the primary queue [[Nsoperationqueue Mainqueue] addoperationwithblock:^{NSLog (@ "Download start%@-%@", [Nsthread CurrentThread] , nil); }];} /** nsblockoperation */-(void) opdemo2{for (int i = 0; i < i++) {//Specify a block operation Nsblockoperation *op 1 = [nsblockoperation blockoperationwithblock:^{NSLog (@ "Download start%@-%@", [Nsthread CurrentThread], @ (i)); }]; Add a block action to the queue [Self.queue ADDOPERATION:OP1]; }} #pragma the dispatch method of Mark invocation-(void) Download: (ID) obj{NSLog (@ "Download starts%@-%@", [Nsthread CurrentThread], obj);} /** nsinvocationoperation */-(void) opdemo1{for (int i = 0; i < i++) {nsinvocationoperation *OP1 = [[NS] Invocationoperation Alloc] initwithtarget:self selector: @selector (Download:) object:@ (i)]; If it is started directly, it will be executed in the main thread//[OP1 start]; Added to the queue, it creates a new thread, asynchronously executes [self.queue ADDOPERATION:OP1]; }} @end//header file @interface Nsoperation:nsobject {-(ID) init;//Designated initializer//start task- (void) start;-(void) main;//whether the task is canceled-(bool) iscancelled;-(void) cancel;//is executing-(BOOL) isexecuting;//is complete execution-(BOOL) isfinished;-(BOOL) isconcurrent;-(BOOL) isready;//method used by the dependent operation between queues-(void) Adddependency: (Nsoperation *) op;-(void) Removedependency: (nsoperation *) op;//Queue Group Dependency-(Nsarray *) dependencies;//Queue Priority-(nsoperationqueuepriority) queuepriority;-(void) setqueuepriority: (nsoperationqueuepriority) p; #if ns_blocks_available-(void (^) (void)) Completionblock ns_available (10_6, 4_0);-(void) Setcompletionblock: (void (^) (void)) block ns_available (10_6, 4_0); endif//wait until completion-(void) waituntilfinished ns_available (10_6, 4_0);-(double) threadpriority ns_available (10_6, 4_0);-( void) SetThreadPriority: (double) p ns_available (10_6, 4_0); @endNS_CLASS_AVAILABLE (10_6, 4_0) @interface nsblockoperation:nsoperation {@private ID _private2; void *_reserved2;} #if ns_blocks_available+ (ID) Blockoperationwithblock: (void (^) (void)) block;-(void) Addexecutionblock: (void (^) (void )) block;-(Nsarray *) executionblocks; #endif@end-(ID) Initwithtarget: (ID) Target selector: (SEL) SEL object: (ID) arg;-(ID) initwithinvocation: (Nsinvocation *) inv;//designated initializer-(nsinvocation *) invocation;-(ID) result; @endFOUNDATION_EXPORT NSString * const Nsinvocationoperationvoidresultexception ns_available (10_5, 2_0); Foundation_export NSString * Const nsinvocationoperationcancelledexception ns_available (10_5, 2_0); N (void) Addoperation: (Nsoperation *) op;-(void) Addoperations: (Nsarray *) Ops waituntilfinished: (BOOL) Wait Ns_ AVAILABLE (10_6, 4_0); #if ns_blocks_available-(void) Addoperationwithblock: (void (^) (void)) block ns_available (10_6, 4 _0); #endif//Queue Group-(Nsarray *) operations;-(Nsuinteger) operationcount ns_available (10_6, 4_0);//MAX Concurrent number-(Nsinteger) maxconcurrentoperationcount;-(void) Setmaxconcurrentoperationcount: (Nsinteger) Cnt;enum { Nsoperationqueuedefaultmaxconcurrentoperationcount = -1};//Set Pause-(void) setsuspended: (BOOL) b;-(BOOL) issuspended;// Set name-(void) SetName: (NSString *) n ns_available (10_6, 4_0);-(NSString*) name Ns_available (10_6, 4_0);//Cancel All people go-(void) cancelalloperations;//wait for all tasks to complete-(void) waituntilalloperationsarefinished;//Current queue + (ID) currentqueue ns_available (10_6, 4_0);//home column + (ID) mainqueue NS_ AVAILABLE (10_6, 4_0); @end
iOS multi-thread nsoperation and Nsoperationqueue