码迷,mamicode.com
首页 > 移动开发 > 详细

iOS开发多线程篇—线程间的通信

时间:2016-05-12 20:23:23      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

一、简单说明
线程间通信:在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 "CKViewController.h"  
@interface CKViewController ()  
@property (weak, nonatomic) IBOutlet UIImageView *iconView;  
@end  

@implementation CKViewController  

- (void)viewDidLoad  
{  
    [super viewDidLoad];  
}  

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

// 在子线程中调用download方法下载图片  
    [self performSelectorInBackground:@selector(download) withObject:nil];  
}  



-(void)download  
{  
    //1.根据URL下载图片  
    //从网络中下载图片  
    NSURL *urlstr=[NSURL URLWithString:@"fdsf"];  

    //把图片转换为二进制的数据  
    NSData *data=[NSData dataWithContentsOfURL:urlstr];//这一行操作会比较耗时  

    //把数据转换成图片  
    UIImage *image=[UIImage imageWithData:data];  

    //2.回到主线程中设置图片  
    [self performSelectorOnMainThread:@selector(settingImage:) withObject:image waitUntilDone:NO];  
}  



//设置显示图片  
-(void)settingImage:(UIImage *)image  
{  
    self.iconView.image=image;  
}  

@end  

代码2:


#import "CKViewController.h"  
#import <NSData.h>  

@interface CKViewController ()  
@property (weak, nonatomic) IBOutlet UIImageView *iconView;  
@end  

@implementation CKViewController  

- (void)viewDidLoad  
{  
    [super viewDidLoad];  
}  


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event  
{  
// 在子线程中调用download方法下载图片  

    [self performSelectorInBackground:@selector(download) withObject:nil];  
}  


-(void)download  
{  

    //1.根据URL下载图片  
    //从网络中下载图片  
    NSURL *urlstr=[NSURL URLWithString:@"fdsf"];  

    //把图片转换为二进制的数据  
    NSData *data=[NSData dataWithContentsOfURL:urlstr];//这一行操作会比较耗时  

    //把数据转换成图片  
    UIImage *image=[UIImage imageWithData:data];  

    //2.回到主线程中设置图片  
    //第一种方式  
//    [self performSelectorOnMainThread:@selector(settingImage:) withObject:image waitUntilDone:NO];  

    //第二种方式  
    //    [self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];  

    //第三种方式  
   [self.iconView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];  
}  


//设置显示图片  
//-(void)settingImage:(UIImage *)image  
//{  
//    self.iconView.image=image;  
//}  

@end  

iOS开发多线程篇—线程间的通信

标签:

原文地址:http://blog.csdn.net/c386890506/article/details/51352208

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