线程间通信:1.一个线程传递数据给另一个线程 2.一个线程执行完任务后转到下一个线程继续执行任务。
常用方法:
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullableid)arg waitUntilDone:(BOOL)wait modes:(nullableNSArray *)array;
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullableid)arg waitUntilDone:(BOOL)wait;// equivalent to the first method with kCFRunLoopCommonModes
小例子:图片下载
#import"ViewController.h"
@interfaceViewController()
@property(weak,nonatomic)IBOutletUIImageView*imageView;
@end
@implementationViewController
#pragma mark ----------------------
#pragma Events
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event
{
[NSThreaddetachNewThreadSelector:@selector(download)toTarget:selfwithObject:nil];
}
#pragma mark ----------------------
#pragma Methods
//开子线程下载图片,回到主线程刷新UI
-(void)download
{
//1.确定URL
NSURL*url = [NSURLURLWithString:@"http://img4.duitang.com/uploads/blog/201310/18/20131018213446_smUw4.thumb.700_0.jpeg"];
//2.根据url下载图片二进制数据到本地
NSData*imageData = [NSDatadataWithContentsOfURL:url];
//3.转换图片格式
UIImage*image = [UIImageimageWithData:imageData];
NSLog(@"download----%@",[NSThreadcurrentThread]);
//4.回到主线程显示UI
/*
第一个参数:回到主线程要调用哪个方法
第二个参数:前面方法需要传递的参数此处就是image
第三个参数:是否等待
*/
//[self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:NO];
//[self performSelector:@selector(showImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
[self.imageViewperformSelectorOnMainThread:@selector(setImage:)withObject:imagewaitUntilDone:YES];
//self.imageView.image = image;
NSLog(@"---end---");
}
//计算代码段执行时间的第一种方法
-(void)download1
{
//0.000018
//0.166099
//1.确定URL
NSURL*url = [NSURLURLWithString:@"http://img4.duitang.com/uploads/blog/201310/18/20131018213446_smUw4.thumb.700_0.jpeg"];
NSDate*start = [NSDatedate];//获得当前的时间
//2.根据url下载图片二进制数据到本地
NSData*imageData = [NSDatadataWithContentsOfURL:url];
NSDate*end = [NSDatedate];//获得当前的时间
NSLog(@"%f",[endtimeIntervalSinceDate:start]);
//3.转换图片格式
UIImage*image = [UIImageimageWithData:imageData];
//4.显示UI
self.imageView.image= image;
}
//计算代码段执行时间的第二种方法
-(void)download2
{
//1.确定URL
NSURL*url = [NSURLURLWithString:@"http://img4.duitang.com/uploads/blog/201310/18/20131018213446_smUw4.thumb.700_0.jpeg"];
CFTimeIntervalstart =CFAbsoluteTimeGetCurrent();
//2.根据url下载图片二进制数据到本地
NSData*imageData = [NSDatadataWithContentsOfURL:url];
CFTimeIntervalend =CFAbsoluteTimeGetCurrent();
NSLog(@"end-start = %f---%f---%f",end - start,end,start);
//3.转换图片格式
UIImage*image = [UIImageimageWithData:imageData];
//4.显示UI
self.imageView.image= image;
}
//更新UI操作
-(void)showImage:(UIImage*)image
{
self.imageView.image= image;
NSLog(@"UI----%@",[NSThreadcurrentThread]);
}