用NSThread,线程间的通信

Posted on 2016-07-16 17:36  柠檬片  阅读(124)  评论(0)    收藏  举报
线程间通信常用方法
只要是对象,都可以掉用以下方法

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;

- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;

 

示例:

 1 #import "ViewController.h"
 2 
 3 @interface ViewController ()
 4 @property (weak, nonatomic) IBOutlet UIImageView *imgView;
 5 
 6 @end
 7 
 8 @implementation ViewController
 9 
10 -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
11 {
12 //    http://pic1.ooopic.com/uploadfilepic/sheji/2010-01-13/OOOPIC_1982zpwang407_20100113f68118f451f282f4.jpg
13     
14     [NSThread detachNewThreadSelector:@selector(download) toTarget:self withObject:nil];
15 }
16 
17 -(void)download2
18 {
19     //下载图片
20     //1.获取url地址
21     NSURL *url = [NSURL URLWithString:@"http://pic1.ooopic.com/uploadfilepic/sheji/2010-01-13/OOOPIC_1982zpwang407_20100113f68118f451f282f4.jpg"];
22     //2.下载图片
23     NSDate *start = [NSDate date];
24     NSData *data = [NSData dataWithContentsOfURL:url];
25     NSDate *end = [NSDate date];
26     
27     NSLog(@"+++++%f",[end timeIntervalSinceDate:start]);
28     //3.把二进制数据转换成图片
29     UIImage *image = [UIImage imageWithData:data];
30     
31     NSLog(@"----%@",[NSThread currentThread]);
32     //4.回到主线程刷新UI
33     //    waitUntilDone:
34     //    [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES];
35     //    [self.imgView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
36     
37     [self.imgView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
38     
39 
40 }
41 -(void)download
42 {
43     //下载图片
44     //1.获取url地址
45     NSURL *url = [NSURL URLWithString:@"http://pic1.ooopic.com/uploadfilepic/sheji/2010-01-13/OOOPIC_1982zpwang407_20100113f68118f451f282f4.jpg"];
46     //2.下载图片
47     CFTimeInterval start = CFAbsoluteTimeGetCurrent();
48     
49     NSData *data = [NSData dataWithContentsOfURL:url];
50     CFTimeInterval end = CFAbsoluteTimeGetCurrent();
51     
52     NSLog(@"+++++%f",end - start);
53     //3.把二进制数据转换成图片
54     UIImage *image = [UIImage imageWithData:data];
55     
56     NSLog(@"----%@",[NSThread currentThread]);
57     //4.回到主线程刷新UI
58 //    waitUntilDone:
59 //    [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES];
60 //    [self.imgView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
61     
62     [self.imgView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
63     
64     
65 
66 
67 }
68 
69 //-(void)showImage:(UIImage *)image
70 //{
71 //    self.imgView.image = image;
72 //     NSLog(@"-showImage---%@",[NSThread currentThread]);
73 //}
74 @end
使用示例