GCD线程通讯

GCD线程通讯

    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        NSLog(@"dispatch_async globalQueue begin !!! %@", [NSThread currentThread]);

        // 耗时操作
        NSString *str = @"https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png";
        NSURL *url = [NSURL URLWithString:str];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        
        // 回主线程,更新图片;
        dispatch_queue_t mainQueue = dispatch_get_main_queue();
        
        // 阻塞当前线程,等待block执行完毕后,向下执行
        //dispatch_sync(mainQueue, ^{
        
        // 不阻塞当前线程,直接执行下面的操作,无需等待block
        dispatch_async(mainQueue, ^{
            NSLog(@"image.size.width...%f", image.size.width);
            NSLog(@"mainQueue !!! %@", [NSThread currentThread]);

            self.imageView.image = image;
        });
        
        NSLog(@"dispatch_async globalQueue end !!! %@", [NSThread currentThread]);

    });

NSThread线程通讯

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSLog(@"Hello World ! 111111  %@", [NSThread currentThread]);
    [NSThread detachNewThreadSelector:@selector(downloadImage) toTarget:self withObject:nil];
    NSLog(@"Hello World ! 222222  %@", [NSThread currentThread]);

}

- (void)downloadImage {
    NSLog(@"downloadImage begin !!! %@", [NSThread currentThread]);
        
    NSString *str = @"http://sinastorage.com/storage.zone.photo.sina.com.cn/zone/img/20161101/eb1721bdb2e5b6d85534833d249a3bff.jpg?&ssig=tW2%2BnBxmjp&KID=sina,slidenews&Expires=1478091012";
    NSURL *url = [NSURL URLWithString:str];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:data];
    
    // 线程通信
    // 子线程回主线程
    // 1.定义一个loadImage方法,为imageView赋值
    //[self performSelectorOnMainThread:@selector(loadImage:) withObject:image waitUntilDone:NO];
    //[self performSelector:@selector(loadImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];
    
    // 2.使用imageView自带的setImage方法赋值
    [imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
    
    NSLog(@"downloadImage end !!! %@", [NSThread currentThread]);
}

- (void)loadImage:(id)obj {
    imageView.image = obj;
    NSLog(@"loadImage end !!! %@", [NSThread currentThread]);

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文首发于我的个人博客:「程序员充电站」[https://itcharge.cn]文章链接:「传送门」[https...
    ITCharge阅读 349,554评论 308 1,927
  • 1. GCD简介 什么是GCD呢?我们先来看看百度百科的解释简单了解下概念 引自百度百科:Grand Centra...
    千寻_544f阅读 426评论 0 0
  • Object C中创建线程的方法是什么?如果在主线程中执行代码,方法是什么?如果想延时执行代码、方法又是什么? 1...
    AlanGe阅读 1,850评论 0 17
  • 减肥是很多人一辈子的事业,经常看励志鸡汤和别人的减肥经验,仿佛一行动起来就能瘦下来。然而减肥并不是一时兴起,否则你...
    智生争冠阅读 337评论 0 0
  • 试试,怎么写连载?
    阿槑爱败家阅读 130评论 0 0