Basics of multithreaded Programming for iOS

Source: Internet
Author: User
<span id="Label3"></p><p><p>Multithreading is a way to address the main thread being blocked and to improve Efficiency.<br></p></p><p><p>First of all we have to learn multithreaded programming to see how it has several ways:</p></p> <ol> <ol> <li><p>Nsthread</p></li> <li><p>Nsoperation</p></li> <li><p>Grand centeral <span style="color: rgb(51, 51, 51); font-family: arial; background-color: rgb(255, 255, 255);">Dispatch</span><br></p></li> </ol> </ol><p><p>Let's see how <span style="color: rgb(255, 0, 0);"><strong>nsthread</strong></span> is created:</p></p><p><p></p></p><pre class="brush:cpp;toolbar: true; auto-links: false;"><pre class="brush:cpp;toolbar:true; auto-links:false;">nsthread *thread = [[nsthread  Alloc]initwithtarget:self selector: @selector (btnsum:)  object:nil];    //through iniit   Creating nsthread  requires manual threading     [thread start];    [thread  cancel];    //the second open and automatic execution  btnSum  is a way to write for yourself     [nsthread  detachnewthreadselector: @selector (btnsum:)  totarget:self withobject:nil]; </pre></pre><pre class="brush:cpp;toolbar: true; auto-links: false;"><pre class="brush:cpp;toolbar:true; auto-links:false;">-  (void) btnsum: (uibutton *) sender {         long sum = 0;         for  (long i = 0; i < 10; i ++)  {         sum += i;         NSLog (@ "number %ld current thred : %@  %@", Sum,[nsthread currentthread ],[nsoperationqueue currentqueue]);             }    } </pre></pre><p><p><span style="color: rgb(0, 0, 0);"><strong><span style="font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">Use Nsthread or directly from the NSObject class method performselectorinbackground:withobject: to create a thread. If you choose thread to implement multi-threading, then Nsthread is the preferred way to use the official recommendation</span></strong></span></p></p><p><p><strong><span style="color: rgb(255, 0, 0);"><br></span></strong></p></p><p><p><strong><span style="color: rgb(255, 0, 0);">Nsoperation</span></strong></p></p><pre class="brush:cpp;toolbar: true; auto-links: false;"><pre class="brush:cpp;toolbar:true; auto-links:false;">/**     nsoperationqueue thread queue *///    1.nsinvocationoperation Operation     nsinvocationoperation *iop  =[[nsinvocationoperation alloc]initwithtarget:self selector: @selector (btnSum:)  object:nil ];        //operation is not executable and requires a queue to be called     [[ nsoperationqueue mainqueue] addoperation:iop];        //2. nsblockoperation        nsblockoperation *bop = [[ Nsblockoperation alloc]init];   //adding actions as a block of code     [bOP  addexecutionblock:^{        [self btnsum:nil];     }];        //added to Thread queue     [self.operationqueue  addoperation:bop]; </pre></pre><p><p>To create a simple nsoperation object, rewrite the Getter method directly<br></p></p><pre class="brush:cpp;toolbar: true; auto-links: false;"><pre class="brush:cpp;toolbar: true; auto-links: false;">-(nsoperationqueue *) operationqueue{if (!_operationqueue) {_operationqueue = [[nsoperationqueue alloc]init];    [_operationqueue setname:@ "queue"]; } return _operationqueue;}</pre></pre><pre class="brush:cpp;toolbar: true; auto-links: false;">nsblockoperation  creation method, You can use the convenient constructor, directly add block    nsblockoperation *bop =  [nsblockoperation blockoperationwithblock:^{        for  (int  i = 0; i < 100; i ++)  {             nslog (@ "%d, Current thread:::%@", i,[nsthread currentthread]);         }    }];    nsblockoperation *aop  = [NSBlockOperation blockOperationWithBlock:^{         for  (int i = 0; i < 100; i ++)  {             nslog (@ "%d, Current thread:::%@", i,[nsthread currentthread]);         }    }];    nsblockoperation  *cop = [nsblockoperation blockoperationwithblock:^{        for   (int i = 0; i < 100; i ++)  {             nslog (@ "%d, Current thread 333333333:::%@", i,[nsthread currentthread] );         }    }];    //add to primary queue     [[nsoperationqueue mainqueue] addoperation:bop];    [[ Nsoperationqueue mainqueue] addoperation:cop];//custom Queue     self.operation =  [[nsoperationqueue alloc]init];    //setting the maximum number of concurrent      Self.operation.maxconcurrentoperationcount = 1;//only perform one operation at the same continuous time//     self.operation.maxconcurrentoperationcount = 4;       [self  Performselectorinbackground: @selector (PRINTNUmber:)  withobject:@ "NSOBJECT"];&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;[SELF.OPERATION&NBSP;ADDOPERATION:AOP ];    [self.operation addoperation:cop];</pre><p><p> <span style="color:rgb (255, 0, 0);"> <strong> GCD </strong> </span> </p> </p><pre class="brush:cpp;toolbar: true; auto-links: false;">/**gcd  Central distribution mechanism  Grand Central Dispatch  function-based, use distribution queue fifo*/    //1. Main thread queue:: equivalent to [nsoperationqueue mainqueue]    //2. global thread queue   background queue    parallel      //3. Custom thread Queue  DISPATCH_QUEUE_SERIAL  serial//                    DISPATCH_QUEUE_CONCURRENT  Parallel     /*    //create a custom queue, default to serial (so add a priority to the East::D Ispatch_queue_priority_default)     dispatch_queue_t myqueue = dispatch_queue_create (" Com.liulei.www.myQueue ", dispatch_queue_priority_default);     //serial queue      // dispatch_async (queue,  Execution Block)   asynchronous     // dispatch_sync (queue,  Execute block) sync     dispatch_async (myqueue, ^{         [self printnumber:@ "GCD"];        [self printnumber:@ "GCD1"];    });             dispatch_async (myqueue, ^{         [self printnumber:@ "GCD2"];    });     */     /*//parallel Queue     dispatch_queue_t conqueue = dispatch_ Queue_create ("conqueue",  dispatch_queue_concurrent);         // A bolck in serial     dispatch_async (conqueue, ^{         //sequential Execution         [self printnumber:@ "G1"];         [self printnumber:@ "G2"];        [ self printnumber:@ "G3"];         //parallel Execution      Dispatch_async (conqueue,  ^{                [self  printnumber:@ "G4"];    });         dispatch_ Async (conqueue, ^{        [self printnumber:@ "G5"];     });     */    //dispatch_after .. Delay operation</pre><p><p><span style="color: rgb(255, 0, 0);"></span></p></p><p style="margin-top: 10px; margin-right: auto; margin-left: auto; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; white-space: normal;"><p style="margin-top: 10px; margin-right: auto; margin-left: auto; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; white-space: normal;"><strong>Since said multi-threaded development, will inevitably be in the multi-threaded communication;<br>Using some of the <span style="color: rgb(255, 0, 0);">NSObject</span> 's class methods, it can be easily done. (nsobject built-in methods to create Threads)</strong></p></p><p style="margin-top: 10px; margin-right: auto; margin-left: auto; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; white-space: normal;"><p style="margin-top: 10px; margin-right: auto; margin-left: auto; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; white-space: normal;"><strong>Do things in the main thread of the application:<br>-(void) performselectoronmainthread: (SEL) aselector withobject: (id) arg waituntildone: (BOOL) wait</strong></p></p><p style="margin-top: 10px; margin-right: auto; margin-left: auto; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; white-space: normal;"><p style="margin-top: 10px; margin-right: auto; margin-left: auto; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; white-space: normal;"><strong>-(void) performselectoronmainthread: (SEL) aselector withobject: (id) arg waituntildone: (BOOL) wait modes: (nsarray *) Array</strong></p></p><p style="margin-top: 10px; margin-right: auto; margin-left: auto; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; white-space: normal;"><p style="margin-top: 10px; margin-right: auto; margin-left: auto; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; white-space: normal;"><strong>To do something in the specified thread:<br>-(void) performselector: (SEL) aselector onthread: (nsthread *) thr withobject: (id) arg waituntildone: (BOOL) wait</strong></p></p><p style="margin-top: 10px; margin-right: auto; margin-left: auto; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; white-space: normal;"><p style="margin-top: 10px; margin-right: auto; margin-left: auto; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; white-space: normal;"><strong>-(void) performselector: (SEL) aselector onthread: (nsthread *) thr withobject: (id) arg waituntildone: (BOOL) wait modes: ( Nsarray *) Array<br>Do things in the current thread:<br>Invokes a method of the receiver on the current thread, using the default mode after a delay.<br>-(void) performselector: (SEL) aselector withobject: (id) anargument afterdelay: (nstimeinterval) delay</strong></p></p><p style="margin-top: 10px; margin-right: auto; margin-left: auto; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; white-space: normal;"><p style="margin-top: 10px; margin-right: auto; margin-left: auto; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; white-space: normal;"><strong>PerformSelector:withObject:afterDelay:inModes:</strong></p></p><p style="margin-top: 10px; margin-right: auto; margin-left: auto; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; white-space: normal;"><p style="margin-top: 10px; margin-right: auto; margin-left: auto; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; white-space: normal;"><strong>Cancels a message sent to the current thread<br>Cancelpreviousperformrequestswithtarget:</strong></p></p><p style="margin-top: 10px; margin-right: auto; margin-left: auto; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; white-space: normal;"><p style="margin-top: 10px; margin-right: auto; margin-left: auto; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; white-space: normal;"><strong>CancelPreviousPerformRequestsWithTarget:selector:object:</strong></p></p><p style="margin-top: 10px; margin-right: auto; margin-left: auto; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; white-space: normal;"><p style="margin-top: 10px; margin-right: auto; margin-left: auto; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; white-space: normal;"><strong>such as when we download data in a thread, after the download is complete to notify the main thread update interface, etc., You can use the following interface:-<br>[self performselectoronmainthread: @selector (updateUI) withobject:nil waituntildone:no];<br>For example, when the download is complete, notify the main thread (ui Thread) so that the app can do other work</strong></p></p><p><p><br></p></p><p><p>Basics of multithreaded Programming for iOS</p></p></span>

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.