ios-Multi-thread nsoperation

Source: Internet
Author: User

  • Objective

    This article is mainly about the use of nsoperation.

  • What

    multithreaded development using nsoperation and Nsoperationqueue is similar to a thread pool, as long as a nsoperation (which requires the use of its subclasses nsinvocationoperation in real development, Nsblockoperation) put it in Nsoperationqueue this queue will start in turn. Nsoperationqueue is responsible for the management and execution of all nsoperation, in this process可以更加容易管理线程总数和控制线程之间的依赖关系。

    Nsoperation uses him to create threading operations, and thread operations are performed only in the threads queue in a child thread.

    Nsoperationqueue: There are two types of thread queues.

    • Primary queue
      • [Nsoperationqueue Mainqueue]
      • All tasks added to the main queue (nsoperation) are executed in the main thread.
    • Non-Home row
      • [[Nsoperationqueue Alloc]init]
      • The tasks that are added to this queue are placed in the child threads to be executed.

    Nsoperation common subclasses are used to create threading operations: Nsinvocationoperation and nsblockoperation are essentially no different, but the latter uses block form to organize code, which is relatively convenient to use. You can also create a thread operation with a custom class that inherits from Nsoperation.

  • How

    With the use of nsoperation and nsoperationqueue to achieve multi-threaded programming, a total of three ways, but in fact, these three ways are used Nsoperation sub-class and nsoperationqueue with the implementation of multi-threaded development. These three subclasses are Nsinvocationoperation, Nsblockoperation, and custom-inherited classes that inherit from Nsoperation, the first of which is a system-provided subclass.

    Way One Nsinvocationoperation and Nsoperationqueue collocation

    1. Create a thread operation and implement methods selected by the method selector

      //创建一个线程操作NSInvocationOperation *invocationOperation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(invocationOperation:) object:kurl];//让线程操作开始执行。但是如果这样做的话这个操作将会在主线程中执行,只有将这个操作放进队列,才会开辟一个子线程让这个操作在子线程中执行。//[invocationOperation start];
    2. Create a queue of threads

      NSOperationQueue *operationQueue = [NSOperationQueue new];
    3. Put the created thread operations in the threads queue

      //只有放在线程队列中的线程操作才会在子线程中执行。线程队列负责管理、执行所有的NSOperation[operationQueue addOperation:invocationOperation];
    4. Update UI within the method selected when creating a thread operation

      - (void)invocationOperation:(NSString *)url{    //虽然没有采用NSThread创建线程,但仍可以使用[NSThread currentThread]来获取当前的线程。    NSLog(@"invocationOperation方法所在的线程%@",[NSThread currentThread]); NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:kurl]]; //在子线程中回到主线程更新UI [[NSOperationQueue mainQueue] addOperationWithBlock:^{ imageView.image = [UIImage imageWithData:data]; }];}

      So far the feeling is similar to Nsthread, the next simple analysis of the difference between the two.

      1. The nsthread needs to be started, that is, to manage the claims cycle, whereas operation simply puts the thread operations into the thread queue, and the thread queue manages and executes all nsoperation.

      2. The maximum number of concurrent threads to manage, that is, the number of concurrently executed tasks.

        //默认是-1,不能设为0,如果设置为0就不执行任务。operationQueue.maxConcurrentOperationCount = 1;
      3. Control the dependencies between threads, Nsoperation can set dependencies between the order of execution, for example, make sure that Operation 1 is finished before you can perform operation 2. Threads cannot depend on each other, as a relies on b,b to have a dependency on a.

        //操作1依赖于操作2[invocationOperation1 addDependency:invocationOperation2];
      4. Cancellation, pause, resume of a queue

        • As long as the suspended of the queue is set to Yes, the execution of other tasks in the queue is paused, that is, no further execution of the task is performed

          self.queue.suspended = YES;

          Note: After it is set to paused, it will not be paused immediately, continuing with the currently executing task until the current task is completed and the next task will not be executed, that is, the pause is actually pausing the next task and cannot pause the current task
          Note: Pauses can be resumed, as long as the suspended of the queue is set to No, then the execution of other tasks in the queue is resumed

        • Cancel execution of all tasks in the queue

          [self.queue cancelAllOperations];

          Cancel and pause are the same as canceling the subsequent task, not canceling the task that is currently executing, and canceling is not recoverable

    Mode two Nsblockoperation and Nsoperationqueue collocation, in fact, the way one and the way two no essential difference. Mainly the latter use block form to organize code, use relatively convenient.

    - (void) viewdidload{[Super Viewdidload]; ImageView = [[Uiimageview Alloc]initwithframe:CGRectMake (50,50,200,200)]; [Self. View Addsubview:imageview];1. Create a thread actionNsblockoperation *blockoperation = [Nsblockoperation blockoperationwithblock:^{NSLog (@ "Blockoperation thread%@" on which the thread is operating, [Nsthread CurrentThread]);NSData *data = [NSData datawithcontentsofurl:[Nsurl Urlwithstring:kurl]]; [[Nsoperationqueue Mainqueue] addoperationwithblock:^{NSLog (@ "Update UI on Thread%@", [nsthread CurrentThread]); Imageview.image = [uiimage Imagewithdata:data];}]; }]; //2. Create thread queue nsoperationqueue *operationqueue = [nsoperationqueue new"; //3. Place thread operations in the thread queue [Operationqueue addoperation:blockoperation]; //ps: simplifies the above operation //1. Create a thread queue nsoperationqueue new]; //directly utilizes the addoperationwithblock of the thread queue to add thread operations. [Operationqueue addoperationwithblock:^{nslog (@ "Update UI on which thread %@ ", [nsthread CurrentThread]); }];}

    mode three inherits from the nsoperation of the Nsoperationqueue and the collocation of the sub-class

    1. Create a class that inherits from Nsoperation and override the Main method in the. m file, and the main method is the action that the thread is going to perform. Note that if it is a synchronous operation, this method automatically accesses the auto-free pool of the main thread, and if it is an asynchronous operation, it will not be able to access the auto-free pool to the main thread, and a new auto-release pool in main is required to help manage memory.

    2. Creates a thread queue and puts the thread operations in the threads queue.

      . h
      //CoustomOperation.hNsoperation////Created by GG on 16/2/26. copyright©2016 years GG. All rights reserved. // #import <Foundation/ Foundation.h> #import <uikit/uikit.h> @interface coustomoperation: nsoperation//receive incoming Picture object  @property (nonatomic,retain) uiimageview *imageview; When the class object is initialized, the picture is attempted to be passed into the class. -(Instancetype) Initwithimageview: (uiimageview *) ImageView;  @end             
      . m
      //Coustomoperation.mNsoperation//Created by GG on 16/2/26.copyright©2016 years GG. All rights reserved.//#import"CoustomOperation.h"#define KURL @"http://store.storeimages.cdn-apple.com/8748/as-images.apple.com/is/image/AppleInc/aos/published/images/s/38/ S38ga/rdgd/s38ga-rdgd-sel-201601?wid=848&hei=848&fmt=jpeg&qlt=80&op_sharpen=0&resmode= bicub&op_usm=0.5,0.5,0,0&iccembed=0&layer=comp&.v=1454777389943 "@implementationcoustomoperation-(Instancetype) Initwithimageview: (Uiimageview *) imageview{Self = [Super Init];if (Self) {Self. ImageView = ImageView; }ReturnSelf;} - (void) main{//create a new auto-free pool, because if it is a synchronous operation, the method can automatically access the auto-free pool of the main thread, and if it is performed asynchronously, it will not be able to access the auto-release pool to the main thread.  @autoreleasepool {nslog (@ " Get the thread where the picture is%@ ", [nsthread CurrentThread]); nsdata *imagedata = [nsdata Datawithcontentsofurl:[nsurl Urlwithstring:kurl]; [[nsoperationqueue Mainqueue] addoperationwithblock:^{ NSLog (@ "Update UI on Thread%@", [nsthread CurrentThread]); self.imageview.image = [uiimage Imagewithdata:imagedata]; }]; }} @end             
      Viewcontroller.m
      - (void)viewDidLoad{      [super viewDidLoad];      imageView = [[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 200, 200)]; [self.view addSubview:imageView]; CoustomOperation *coustomOperation = [[CoustomOperation alloc] initWithImageView:(UIImageView *)imageView]; NSOperationQueue *operationQueue = [NSOperationQueue new]; // [operationQueue addOperation:coustomOperation];}
Summary: In these three ways, feeling one is the most troublesome, the way two is relatively concise, and the way shift is suitable for encapsulating a thread operation.

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.