一、简单说明
线程间通信:在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信
线程间通信的体现
1个线程传递数据给另1个线程
在1个线程中执行完特定任务后,转到另1个线程继续执行任务
线程间通信常用方法
- (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 "YYViewController.h"
- @interface YYViewController ()
- @property (weak, nonatomic) IBOutlet UIImageView *iconView;
- @end
-
- @implementation YYViewController
-
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- }
-
- -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
- {
-
- [self performSelectorInBackground:@selector(download) withObject:nil];
- }
-
-
-
- -(void)download
- {
-
-
- NSURL *urlstr=[NSURL URLWithString:@"fdsf"];
-
-
- NSData *data=[NSData dataWithContentsOfURL:urlstr];
-
-
- UIImage *image=[UIImage imageWithData:data];
-
-
- [self performSelectorOnMainThread:@selector(settingImage:) withObject:image waitUntilDone:NO];
- }
-
-
-
- -(void)settingImage:(UIImage *)image
- {
- self.iconView.image=image;
- }
-
- @end
代码2:
-
- #import "YYViewController.h"
- #import <NSData.h>
-
- @interface YYViewController ()
- @property (weak, nonatomic) IBOutlet UIImageView *iconView;
- @end
-
- @implementation YYViewController
-
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- }
-
-
- -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
- {
-
- [self performSelectorInBackground:@selector(download) withObject:nil];
- }
-
-
- -(void)download
- {
-
-
-
- NSURL *urlstr=[NSURL URLWithString:@"fdsf"];
-
-
- NSData *data=[NSData dataWithContentsOfURL:urlstr];
-
-
- UIImage *image=[UIImage imageWithData:data];
-
-
-
-
-
-
-
-
- [self.iconView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
- }
-
-
-
- @end
iOS开发多线程篇—线程间的通信
原文:http://www.cnblogs.com/Ghosgt/p/5992401.html