zoukankan      html  css  js  c++  java
  • iOS多线程---GCD中线程的通信

    在子线程的任务完成后,有时候需要从子线程回到主线程,刷新UI。 从子线程中回到主线程,以前已经写过一种方法:

       [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];

    现在GCD又提供了一种方法:

      dispatch_async(dispatch_get_main_queue(), ^{             
              self.imageView.image=image;          
      });

    示例代码:

    //
    //  ViewController.m
    //  GCDTest
    //
    //  Created by 登 on 2017/6/16.
    //  Copyright © 2017年 登. All rights reserved.
    //
    
    #import "ViewController.h"
    
    @interface ViewController ()
    @property (weak, nonatomic) IBOutlet UIImageView *imageView;
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        NSLog(@"主线程----%@",[NSThread mainThread]);
    
    }
    
    -(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event
    {
        //1 获取一个全局队列
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        
        // 2 把任务添加到队列中执行
        dispatch_async(queue, ^{
            
            //打印当前的线程
            NSLog(@"%@",[NSThread currentThread]);
            
            //3.从网络下载图片
            NSURL *urlStr = [NSURL URLWithString:@"http://h.hiphotos.baidu.com/baike/w%3D268/sign=30b3fb747b310a55c424d9f28f444387/1e30e924b899a9018b8d3ab11f950a7b0308f5f9.jpg"];
            NSData *data = [NSData dataWithContentsOfURL:urlStr];
            UIImage *image = [UIImage imageWithData:data];
            
            //提示
            NSLog(@"图片加载完毕");
            
            //4.回到主线程,展示图片
           // [self.imageView performSelectorOnMainThread:@selector(setImageView:) withObject:image waitUntilDone:NO];
            dispatch_async(dispatch_get_main_queue(), ^{
                _imageView.image = image;
                
                NSLog(@"%@",[NSThread currentThread]);
            });
        });
        
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
    }
    
    @end

    打印结果:

    2017-06-16 17:55:45.848 GCDTest[15011:2269875] 主线程----<NSThread: 0x60800007f600>{number = 1, name = main}

    2017-06-16 17:56:43.391 GCDTest[15011:2269966] <NSThread: 0x60000026b980>{number = 3, name = (null)}

    2017-06-16 17:56:43.463 GCDTest[15011:2269966] 图片加载完毕

    2017-06-16 17:56:43.463 GCDTest[15011:2269875] <NSThread: 0x60800007f600>{number = 1, name = main}

     

    本文参考:http://www.cnblogs.com/wendingding/p/3807265.html

  • 相关阅读:
    mybatis动态SQl中int类型字段为0 SQl语句不拼接
    Ansible学习(pyenv与virtualenv)
    word
    github学习
    OpenStack搭建遇到的问题2(组件配置错误了,别重装全部,就把模块卸载就行了)
    OpenStack搭建遇到的问题
    Ubuntu 17.04 安装
    docker学习(一)
    MySQL安装
    来自Google的响应式——Agera
  • 原文地址:https://www.cnblogs.com/huadeng/p/7028727.html
Copyright © 2011-2022 走看看