ios--Multi-thread nsoperation

Source: Internet
Author: User

 Nsoperation A, Nsoperation brief introduction 1, Nsoperation Introduction ①. Brief description
    • Nsoperation?: Multi-threaded programming with nsoperation and Nsoperationqueue
Nsoperation and nsoperationqueue The specific steps for Multithreading:
    • (1) Encapsulate the action that needs to be performed into a Nsoperation object first

    • (2) Then add the Nsoperation object to the Nsoperationqueue

    • (3) The system will move the nsoperation out of the nsoperationqueue.

    • (4) Put the operation of the removed Nsoperation package into the new thread?

Subclass of ②.nsoperation
    • Nsoperation is an abstract class, and does not have the ability to encapsulate operations, it must make it a subclass of
There are 3 ways to use the Nsoperation class:
    • (1) nsinvocationoperation

    • (2) Nsblockoperation

    • (3) Customize the subclass inheritance Nsoperation, and implement the internal corresponding method.

2, specific description ①. Nsinvocationoperation sub-class
    • Out of queue, executing in the main thread
    • To execute, you must call [operation start];
//创建操作对象,封装要执行的任务    //NSInvocationOperation   封装操作    NSInvocationOperation *operation=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(test) object:nil]; //执行操作 [operation start]; //一旦执?操作,就会调用target的test方法
②.nsblockoperation sub-class
    • You can append task Addexecutionblock:
    • Also out of the queue, the execution time needs to call [operation start];
//创建NSBlockOperation操作对象    NSBlockOperation *operation=[NSBlockOperation blockOperationWithBlock:^{    // 主线程        NSLog(@"NSBlockOperation------%@",[NSThread currentThread]); }]; //添加操作 // 子线程中执行 [operation addExecutionBlock:^{ NSLog(@"NSBlockOperation1------%@",[NSThread currentThread]); }]; [operation addExecutionBlock:^{ NSLog(@"NSBlockOperation2------%@",[NSThread currentThread]); }]; //开启执行操作 [operation start];
③3. Nsoperationqueue
    • Nsoperationqueue: The nsoperation can be adjusted to start the task, but the default is synchronous execution

    • If you add nsoperation to the Nsoperationqueue (action queue), the system automatically executes the operations in Nsoperation asynchronously

    • Add actions to Nsoperationqueue, automate actions, automatically open threads

II. basic operations 1. Create
    • is automatically executed in the child thread, and the default is concurrency
    • In general, when doing business development, you will define a global custom queue for ease of use.
    //创建NSOperationQueue    // 自己创建的队列,就会在子线程中执行,而且默认是并发     NSOperationQueue * queue=[[NSOperationQueue alloc]init];
2. Adding tasks to the queue
    • Automate actions to automatically open threads
First Kind
[queue addOperation:operation2];
The second Kind
    • Addoperationwithblock: Equivalent to encapsulating nsblockoperation tasks
- (void)addOperationWithBlock:(void (^)(void))block;
Third, custom nsoperation
    • Create a new class to inherit from Nsoperation.
    • For code reusability
    • When you create an object, the main method of the custom nsoperation is called automatically
      • Overriding the Main method
Iv. basic operation of nsoperation 1. Concurrency
    • (1) Number of concurrent: the number of tasks at the same time. For example, open 3 threads at the same time to perform 3 tasks, and the concurrency number is 3.
    • (2) Max concurrency: The maximum number of tasks that can be performed at the same time.
    • (3) The most significant concurrent number of the correlation? method
- (NSInteger)maxConcurrentOperationCount;- (void)setMaxConcurrentOperationCount:(NSInteger)cnt;
说明:If the maximum number of concurrent numbers is not set, then the number of concurrent is determined by the system memory and CPU, the memory may be more than a bit longer, less memory will be less open. ' Note: cannot be set to 0, set to 0 not executed. The default is-1. Set to 1 is serial.提示:Maximum concurrency do not write (less than 5), do not open too much, generally to a number of the appropriate, because although the task is processed on the child thread, but the CPU processing these excessive sub-threads may affect the UI, let the UI change card. 2. Cancellation, pause and resume of the queue (1) Cancel all operations of the queue
    • You can also call the Nsoperation-(void) Cancel method to cancel a single operation
// 取消的是从下个任务开始,当前任务会执行完毕// 取消不能恢复 - (void)cancelAllOperations;
(2) Pausing and resuming queues
    • When set to paused, it will not be paused immediately and will continue to perform the currently executing task until the current task is completed before the next task is executed
    • Pause the next task without pausing the current task
- (void)setSuspended:(BOOL)b; // YES代表暂停队列,NO代表恢复队列- (BOOL)isSuspended; //当前状态
(3) The application of pause and resume: In the TableView interface, the remote Web interface can be downloaded remotely, which will affect the UI and make the user experience worse. In this case, you can set the queue to pause (not cancel the queue) when the user operates the UI (such as scrolling the screen), to stop scrolling, and to resume the queues. 3. Operation priority (1) Set the priority of the nsoperation in the queue, can change the operation of the priority level
- (NSOperationQueuePriority)queuePriority;- (void)setQueuePriority:(NSOperationQueuePriority)p;
(2) The value of the priority level
NSOperationQueuePriorityVeryLow = -8L,NSOperationQueuePriorityLow = -4L,NSOperationQueuePriorityNormal = 0,NSOperationQueuePriorityHigh = 4,NSOperationQueuePriorityVeryHigh = 8//说明:优先级高的任务,调用的几率会更大。
4. Operation Dependency (1) nsoperation can be set up between dependencies to ensure the order of execution, if you must let operation a after the execution, to perform operation B, you can write as follows
// 操作B依赖于操作A
(2) You can create a dependency between nsoperation of different queue
    • Cannot be cyclic dependent (not a depends on b,b and depends on a).
    • 注意:Be sure to set it up before adding it.
    • 提示:The order in which tasks are added does not determine the order of execution, and the order of execution depends on dependencies. The purpose of using operation is to let developers no longer care about threads.
5. Monitoring of the operation
    • Can listen for an operation completed
- (void (^)(void))completionBlock;- (void)setCompletionBlock:(void (^)(void))block;

ios--Multi-thread nsoperation

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.