IOS 并发

苹果官方文档

doc

主线程 main Thread

ios中我们写的代码是被Event来调用
主线程 有一个 run loop用于接受Events
主线程 用于处理界面接触的Event
Event处理代码运行时候会阻塞主线程

三种实现线程的方法

  1. //进入后台进程 执行一个耗时的方法
    [self performSelectorInBackground:@selector(backWork) withObject:nil];
    //后台执行的方法
    -(void) backWork{
        NCLog(@"background thread %@",[NSThread currentThread]); 
        sleep(5);
        //回到主线程 
        [self performSelectorOnMainThread:@selector(mainWork) withObject:nil waitUntilDone:NO];
    }
    
    -(void) mainWork{
        NCLog(@"main  thread %@",[NSThread currentThread]);
    [self.indicator stopAnimating];
    }
    
  2. NSBlockOperation

 //定义 一个task
     NSBlockOperation *op=[NSBlockOperation blockOperationWithBlock:^{
        NCLog(@"NSBlockOperation xxx....");
         sleep(5);
        [self performSelectorOnMainThread:@selector(mainWork) withObject:nil waitUntilDone:NO];
    }];
    //把task 加入到执行队列
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    [queue addOperation:op];
  1. GCD 大中枢 相对NSOperation是更底层的框架.
    用了block代码更加简洁

“`
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NCLog(@”dispatch_async xxx….”);
[self.indicator startAnimating];
sleep(5); dispatch_async(dispatch_get_main_queue(), ^{
[self mainWork];
[self.indicator stopAnimating];

    });
});

“`

参考 http://blog.csdn.net/totogo2010/article/details/8016129

    原文作者:hqman
    原文地址: https://segmentfault.com/a/1190000002749670
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞