1、簡單說明網絡
線程間通訊:在1個進程中,線程每每不是孤立存在的,多個線程之間須要常常進行通訊app
線程間通訊的體現atom
1個線程傳遞數據給另1個線程url
在1個線程中執行完特定任務後,轉到另1個線程繼續執行任務spa
線程間通訊經常使用方法線程
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;code
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;orm
線程間通訊示例 – 圖片下載blog
代碼1:進程
1 // 2 // YYViewController.m 3 // 06-NSThread04-線程間通訊 4 // 5 // Created by apple on 14-6-23. 6 // Copyright (c) 2014年 itcase. All rights reserved. 7 // 8 9 #import "YYViewController.h" 10 @interface YYViewController () 11 @property (weak, nonatomic) IBOutlet UIImageView *iconView; 12 @end 13 14 @implementation YYViewController 15 16 - (void)viewDidLoad 17 { 18 [super viewDidLoad]; 19 } 20 21 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 22 { 23 24 // 在子線程中調用download方法下載圖片 25 [self performSelectorInBackground:@selector(download) withObject:nil]; 26 } 27 28 29 30 -(void)download 31 { 32 //1.根據URL下載圖片 33 //從網絡中下載圖片 34 NSURL *urlstr=[NSURL URLWithString:@"fdsf"]; 35 36 //把圖片轉換爲二進制的數據 37 NSData *data=[NSData dataWithContentsOfURL:urlstr];//這一行操做會比較耗時 38 39 //把數據轉換成圖片 40 UIImage *image=[UIImage imageWithData:data]; 41 42 //2.回到主線程中設置圖片 43 [self performSelectorOnMainThread:@selector(settingImage:) withObject:image waitUntilDone:NO]; 44 } 45 46 47 48 //設置顯示圖片 49 -(void)settingImage:(UIImage *)image 50 { 51 self.iconView.image=image; 52 } 53 54 @end
代碼2:
1 // 2 // YYViewController.m 3 // 06-NSThread04-線程間通訊 4 // 5 // Created by apple on 14-6-23. 6 // Copyright (c) 2014年 itcase. All rights reserved. 7 // 8 9 #import "YYViewController.h" 10 #import <NSData.h> 11 12 @interface YYViewController () 13 @property (weak, nonatomic) IBOutlet UIImageView *iconView; 14 @end 15 16 @implementation YYViewController 17 18 - (void)viewDidLoad 19 { 20 [super viewDidLoad]; 21 } 22 23 24 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 25 { 26 // 在子線程中調用download方法下載圖片 27 28 [self performSelectorInBackground:@selector(download) withObject:nil]; 29 } 30 31 32 -(void)download 33 { 34 35 //1.根據URL下載圖片 36 //從網絡中下載圖片 37 NSURL *urlstr=[NSURL URLWithString:@"fdsf"]; 38 39 //把圖片轉換爲二進制的數據 40 NSData *data=[NSData dataWithContentsOfURL:urlstr];//這一行操做會比較耗時 41 42 //把數據轉換成圖片 43 UIImage *image=[UIImage imageWithData:data]; 44 45 //2.回到主線程中設置圖片 46 //第一種方式 47 // [self performSelectorOnMainThread:@selector(settingImage:) withObject:image waitUntilDone:NO]; 48 49 //第二種方式 50 // [self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO]; 51 52 //第三種方式 53 [self.iconView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO]; 54 } 55 56 57 //設置顯示圖片 58 //-(void)settingImage:(UIImage *)image 59 //{ 60 // self.iconView.image=image; 61 //} 62 63 @end