Multi-thread (NSOperation) for iOS development practices)

Source: Internet
Author: User

Multi-thread (NSOperation) for iOS development practices)

NSOperation encapsulates GCD (underlying layer) and is more object-oriented.

NSOperation

With NSOperation and NSOperationQueue, you can also implement multi-threaded programming.

Detailed steps for implementing multiple threads in NSOperation and NSOperationQueue

1. encapsulate the operations to be executed into an NSOperation object.

2. Add the NSOperation object to the NSOperationQueue.

3. the system automatically retrieves NSOperation from NSOperationQueue.

4. Put the extracted NSOperation encapsulated operations in a new thread for execution.

NSOperation is an abstract class and does not have the ability to encapsulate operations. It must be used as a subclass.

1. NSInvocationOperation

1.1 create an NSInvocationOperation object

-(Id) initWithTarget :( id) target selector :( SEL) sel object :( id) arg;

1.2. Note:

By default, after the start method is called, a new thread is not opened to execute the operation, but the operation is executed synchronously in the current thread.

The operation is performed asynchronously only when NSOperation is put in an NSOperationQueue.

-(Void) viewDidLoad {[super viewDidLoad]; // create a queue NSOperationQueue * queue = [[NSOperationQueue alloc] init]; // create NSInvocationOperation * operation = [[NSInvocationOperation alloc] initWithTarget: self selector: @ selector (download) object: nil]; // operation calls start directly, yes synchronous execution (the operation is executed in the current thread) // [operation start]; // Add the operation to the queue and perform the [queue addOperation: operation];}

2. NSBlockOperation

2.1 create an NSBlockOperation object

+ (Id) blockOperationWithBlock :( void (^) (void) block;

2.2 add more operations using the addExecutionBlock Method

-(Void) addExecutionBlock :( void (^) (void) block;

2.3. Note: as long as the NSBlockOperation encapsulated operand is greater than 1, the operation will be executed asynchronously.

-(Void) viewDidLoad {[super viewDidLoad]; NSBlockOperation * operation = [NSBlockOperation blockOperationWithBlock: ^ {NSLog (@ "--- download image ---- 1 --- % @", [NSThread currentThread]);}]; [operation addExecutionBlock: ^ {NSLog (@ "--- download image ---- 2 --- % @", [NSThread currentThread]);}]; [operation addExecutionBlock: ^ {NSLog (@ "--- download image ---- 3 --- % @", [NSThread currentThread]) ;}]; // number of tasks> 1, [operation start];}
-(Void) viewDidLoad {[super viewDidLoad]; NSBlockOperation * operation1 = [NSBlockOperation blockOperationWithBlock: ^ {NSLog (@ "--- download image ---- 1 --- % @", [NSThread currentThread]);}]; NSBlockOperation * operation2 = [NSBlockOperation blockOperationWithBlock: ^ {NSLog (@ "--- download image ---- 2 --- % @", [NSThread currentThread]);}]; NSBlockOperation * operation3 = [NSBlockOperation blockOperationWithBlock: ^ {NSLog (@ "--- download image ---- 3 --- % @", [NSThread currentThread]);}]; // 1. create a queue NSOperationQueue * queue = [[NSOperationQueue alloc] init]; // create a queue column, operations added to the main queue will be executed in a synchronous serial // NSOperationQueue * queue = [NSOperationQueue mainQueue]; // 2. add the operation to the queue (automatic asynchronous execution) [queue addOperation: operation1]; [queue addOperation: operation2]; [queue addOperation: operation3];}

3. The custom subclass inherits NSOperation and implements corresponding internal methods.

To customize NSOperation, follow these steps:

Override-(void) main method to implement the task to be executed

Override-note of (void) main method

Create an automatic release pool by yourself (because the automatic release pool of the main thread cannot be accessed for asynchronous operations)

The-(BOOL) isCancelled method is often used to check whether the operation is canceled and respond to the cancellation.

NSOperationQueue

1. NSOperationQueue: NSOperation can call the start method to execute the task, but it is executed synchronously by default. If you add NSOperation to NSOperationQueue (Operation Queue), the system will automatically perform operations in NSOperation asynchronously.

2. Add the operation to NSOperationQueue:

-(Void) addOperation :( NSOperation *) op;

-(Void) addOperationWithBlock :( void (^) (void) block;

-(Void) viewDidLoad {[super viewDidLoad]; NSOperationQueue * queue = [[NSOperationQueue alloc] init]; [queue addOperationWithBlock: ^ {NSLog (@ "Download image ----- % @", [NSThread currentThread]);}];}
3. Maximum concurrency

Concurrency refers to the number of tasks executed at the same time. For example, if three threads are enabled to execute three tasks at the same time, the number of concurrent jobs is three.

Related methods for maximum concurrency

-(NSInteger) maxConcurrentOperationCount;

-(Void) setMaxConcurrentOperationCount :( NSInteger) cnt;

-(Void) viewDidLoad {[super viewDidLoad]; // 1. create a queue (non-main queue column) NSOperationQueue * queue = [[NSOperationQueue alloc] init]; // 2. set the maximum concurrency (up to three concurrently executed tasks) queue. maxConcurrentOperationCount = 3; // 3. add operations to the queue (automatic asynchronous task execution, concurrency) NSBlockOperation * operation1 = [NSBlockOperation blockOperationWithBlock: ^ {NSLog (@ "Download image 1 --- % @", [NSThread currentThread]);}]; NSBlockOperation * operation2 = [NSBlockOperation blockOperationWithBlock: ^ {NSLog (@ "Download Image 2 --- % @", [NSThread currentThread]);}]; NSBlockOperation * operation3 = [NSBlockOperation blockOperationWithBlock: ^ {NSLog (@ "Download Image 3 --- % @", [NSThread currentThread]);}]; NSBlockOperation * operation4 = [NSBlockOperation blockOperationWithBlock: ^ {NSLog (@ "Download Image 4 --- % @", [NSThread currentThread]);}]; NSInvocationOperation * operation5 = [[NSInvocationOperation alloc] initWithTarget: self selector: @ selector (download) object: nil]; [queue addOperation: operation1]; [queue addOperation: operation2]; [queue addOperation: operation3]; [queue addOperation: operation4]; [queue addOperation: operation5];}
4. Operation dependency

Dependencies can be set between NSOperation to ensure the execution sequence.

For example, you must have operation A complete before you can perform Operation B.

[OperationB addDependency: operationA]; // operation B depends on operation

You can create dependencies between NSOperation of different queue. However, note: do not depend on each other. For example, A depends on B and B depends on.


-(Void) viewDidLoad {[super viewDidLoad];/** assume there are three operations, A, B, and C. The requirements are as follows: 1. all three operations are executed asynchronously. operation C depends on Operation B 3. operation B depends on operation A * // 1. create a queue (non-main queue column) NSOperationQueue * queue = [[NSOperationQueue alloc] init]; // 2. create three NSBlockOperation * operationA = [NSBlockOperation blockOperationWithBlock: ^ {NSLog (@ "A1 --- % @", [NSThread currentThread]);}]; NSBlockOperation * operationB = [NSBlockOperation blockOperationWithBlock: ^ {NSLog (@ "B --- % @", [NSThread currentThread]);}]; NSBlockOperation * operationC = [NSBlockOperation blockOperationWithBlock: ^ {NSLog (@ "C --- % @", [NSThread currentThread]);}]; // sets the dependency [operationB addDependency: operationA]; [operationC addDependency: operationB]; // 3. add operations to the queue (automatic asynchronous task execution) [queue addOperation: operationC]; [queue addOperation: operationA]; [queue addOperation: operationB];}
5. Queue cancellation, suspension, and recovery

5.1 cancel all operations on the queue

-(Void) cancelAllOperations;

Tip: You can also call the NSOperation-(void) cancel Method to cancel a single operation.

5.2 pause and restore a queue

-(Void) setsuincluded :( BOOL) B; // YES indicates that the queue is suspended, and NO indicates that the queue is restored.

-(BOOL) issuincluded;

6. Operation priority

Sets the priority of NSOperation in the queue to change the operation execution priority.

-(NSOperationQueuePriority) queuePriority;

-(Void) setQueuePriority :( NSOperationQueuePriority) p;

Priority Value

NSOperationQueuePriorityVeryLow =-8L,

NSOperationQueuePriorityLow =-4L,

NSOperationQueuePriorityNormal = 0,

NSOperationQueuePriorityHigh = 4,

NSOperationQueuePriorityVeryHigh = 8

7. Operation listening

You can monitor the completion of an operation.

-(Void (^) (void) completionBlock;

-(Void) setCompletionBlock :( void (^) (void) block;

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.