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

来源:互联网 发布:七招应对网络泄密隐患 编辑:程序博客网 时间:2024/04/30 00:32

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

////  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
运行结果如下:




1 0