zoukankan      html  css  js  c++  java
  • iOS开发--线程通信

     

    线程间的通信主要用于主线程与子线程的,也有用于子线程与子线程的

    介绍下面几种通信方式

    1.利用GCD方式(推荐)

    复制代码
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
        //开一个子线程
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
           //下载图片
            
            NSURL *url = [NSURL URLWithString:@"http://e.hiphotos.baidu.com/image/pic/item/14ce36d3d539b600be63e95eed50352ac75cb7ae.jpg"];
            NSData *data = [NSData dataWithContentsOfURL:url];
            UIImage *img = [UIImage imageWithData:data];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //回到主线程
                self.imgVIew.image = img;
            });
            
            //在这里使用同步还是异步,区别是前者是按顺序依次执行,后者是先执行到最后再回到主线程
            NSLog(@"________");
        });
    }
    复制代码

    利用这种方式可以轻松地控制线程间的跳转通信

    2.利用系统方法

    复制代码
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
       
        //创建子线程
        [self performSelectorInBackground:@selector(downLoad) withObject:nil];
    }
    
    
    //在子线程中下载图片
    - (void)downLoad {
        
        NSURL *url = [NSURL URLWithString:@"http://e.hiphotos.baidu.com/image/pic/item/e7cd7b899e510fb34395d1c3de33c895d0430cd1.jpg"];
       
        NSData *data = [NSData dataWithContentsOfURL:url];
        
        UIImage *img = [UIImage imageWithData:data];
        
        //下载完毕,返回给主线程图片    
        [self.imgVIew performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:img waitUntilDone:YES];
        
    }
    复制代码

    补充:也可以使用

    [self performSelectorOnMainThread:@selector(setImg:) withObject:img waitUntilDone:YES];这个方法返回主线程图片

    @selector(这里面其实就是主线程中image属性的set方法)

    3.使用NSOperation方式

    与GCD类似

    复制代码
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
        
        [[[NSOperationQueue alloc] init] addOperationWithBlock:^{
            //下载图片
            NSURL *url = [NSURL URLWithString:@"http://e.hiphotos.baidu.com/image/pic/item/e7cd7b899e510fb34395d1c3de33c895d0430cd1.jpg"];
            
            NSData *data = [NSData dataWithContentsOfURL:url];
            
            UIImage *img = [UIImage imageWithData:data];
            
            //回到主线程
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                self.imgView.image = img;
            }];
            
        }];
    
    }
     
  • 相关阅读:
    关于VS2008单元测试中加载配置文件的问题
    面向对象控与python内存泄漏
    热酷,新的领域,新的发展
    [思想火花]:函数命名及参数
    使用AuthToken架构保护用户帐号验证Cookie的安全性
    竟然遇到取FormAuthentication的值取不出来的情况
    新头衔:热酷高级python软件工程师,你问我去热酷干嘛?
    浅谈滚服游戏如果实现一键合服
    基础
    简介
  • 原文地址:https://www.cnblogs.com/wanghuaijun/p/5326137.html
Copyright © 2011-2022 走看看