NSOperation for iOS multi-thread programming
There are two NSOperation methods:
1>. NSInvocationOperation: creates an operation and points it to the executed code segment with selecter.
2>. NSBlockOperation: Create an operation and place the executed code in the block.
1. NSInvocationOperation multithreading method:
Creation method:
- (void)invocationOperation {NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run1) object:nil];NSOperationQueue *queue = [[NSOperationQueue alloc] init];[queue addOperation:operation1];}
- (void)run1{NSLog(@runing1---%@,[NSThread currentThread]);}
2. NSBlockOperation multithreading method:
Creation method:
- (void)blockOperation1 {NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{NSLog(@blockOperation---%@,[NSThread currentThread]);}];operation.completionBlock = ^{NSLog(@finish!-----);};NSOperationQueue *queue = [[NSOperationQueue alloc] init];[queue addOperation:operation];}
3. Refresh the UI from the subthread back to the main thread:
performSelectorOnMainThread: withObject: waitUntilDone:
4. The execution sequence of multiple operations in the queue can be set.
Set the dependency between operation before adding to queue:
[operation2 addDependency:operation1];
Operation2 depends on operation1 => 2 and runs after 1. in this case, if there are only two operations in the queue, the sub-thread will not be created. Only the main thread and the sub-thread of operation1. after all, it is a waste to open a sub-thread in sequence.
5. You can set the maximum number of threads at the same time in the queue.
queue.maxConcurrentOperationCount = 3;
-- End