多线程之线程间的通信——以及下载文件并保存到指定路径的方法

因为为了有良好的用户交互,都把耗时操作放到新的线程去执行。例如将图片下载(耗时操作执行完毕)后需要将下载的数据放到主线程中去执行,这是就需要线程间的通信。实例验证代码如下:

//
//  ViewController.m
//  线程间通信
//
//  Created by apple on 15/10/20.
//  Copyright (c) 2015年 LiuXun. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()


@end

@implementation ViewController

-(void)viewDidLoad
{
    self.iconView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    self.iconView.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:self.iconView];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //    [self downloadImage];
    [self performSelectorInBackground:@selector(downloadImage) withObject:nil];
}

#pragma mark - 下载图片
-(void)downloadImage
{
    NSLog(@"%@", [NSThread currentThread]);
    @autorelease{
    // 1、URL ,确定一个网络上的资源路径
    NSURL *url = [NSURL URLWithString:@"http://g.hiphotos.baidu.com/image/pic/item/b8014a90f603738def2887edb11bb051f919ec9b.jpg"];
    
    // 2、 通过URL可以下载对应的网络资源,网络资源传输的都是二进制
    NSData *data = [NSData dataWithContentsOfURL:url];
    /*以下用于下载文件并保存到指定的沙盒路径*/
    //    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //    NSString *savePath = [path stringByAppendingPathComponent:@"a.jpg"];
    //    [data writeToFile:savePath atomically:YES];
    //    NSLog(@"%@", path);
    // 3、 将二进制转成图片
    UIImage *image = [UIImage imageWithData:data];
    
    // 4、 将图片显示到组件
    //    self.iconView.image = image;
    //   在这里需要把数据传到主线程,在主线程上更新UI
    
    //     方法一:waitUntilDone:YES 设置如果当前操作没有执行完毕是不会执行以下的代码的
    //    [self performSelectorOnMainThread:@selector(downFinish:) withObject:image waitUntilDone:NO];
    
    // 方法二:waitUntilDone: 表示是否等待@selector()操作执行完毕 再执行下面的代码
    //    [self performSelector:@selector(downFinish:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
    
    // 方法三:
    [self.iconView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
    
    NSLog(@"下载完成"); }
}
-(void)downFinish:(UIImage *)image
{
    NSLog(@"%s-------%@",__func__, [NSThread currentThread]);
    self.iconView.image = image;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end
运行结果如下:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值