码迷,mamicode.com
首页 > 编程语言 > 详细

线程间的通信 代码

时间:2015-09-02 01:53:01      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

#import "ViewController.h"

 

@interface ViewController ()

//图片框 UIImageView

@property (weak, nonatomic) IBOutlet UIImageView *imageView;

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

}

 

//创建一条子线程来执行下载这种耗时操作  点击的方法

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

//    要下载的图片

    NSString *urlString = @"http://p1.yokacdn.com/pic/star/topic/2011/U288P1T117D414828F2577DT20110902111814.jpg";

    

    // 1.在子线程下图片

    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(downloadWebImage:) object:urlString];

//    放到可调用线程池里面

    [thread start];

    

}

 

// 下载网络图片  下载的方法

-(void)downloadWebImage:(NSString *)urlString

{

    NSLog(@"downloadWebImageBegan:%@",[NSThread currentThread]);

    

    // 统一资源定位符 1>把要下载的图片的地址传给统一资源定位符

    NSURL *url = [NSURL URLWithString:urlString];

    

    // 下载图片数据  Contents 内容  下载的内容 2>把统一资源定位符转为数据

    NSData *data = [NSData dataWithContentsOfURL:url];

    

    // 转换图片  3>把数据转为图片

    UIImage *image = [UIImage imageWithData:data];

    

    // 2.在主线程显示图片

    

  //  [self performSelectorOnMainThread:@selector(setupImage:) withObject:image waitUntilDone:YES];

    

//    当图片在子线程下载完以后,会在主线程进行显示

    [self performSelector:@selector(setupImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];

//    打印当前线程

    NSLog(@"downloadWebImageEnd:%@",[NSThread currentThread]);

 

    

}

 

// 设置图片

- (void)setupImage:(UIImage *)image

{

    NSLog(@"setupImage:%@",[NSThread currentThread]);

 

    // 显示图片

    self.imageView.image = image;

}

 

@end

线程间的通信 代码

标签:

原文地址:http://www.cnblogs.com/R-X-L/p/4777437.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!