NSOperation for iOS multi-thread programming

Source: Internet
Author: User

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

 

 


 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.