您的位置:首页 > 理论基础 > 计算机网络

网络多线程-NSThread实现线程间通信

2015-11-27 22:03 405 查看
#import "ViewController.h"

@interface
ViewController ()

@property (weak,
nonatomic) IBOutlet
UIImageView *imageView;

@end

@implementation ViewController

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

    [NSThread
detachNewThreadSelector:@selector(download)
toTarget:self
withObject:nil];

}

//计算代码段的执行时间

-(void)test1

{

    //1.确定url地址

    NSDate *start = [NSDate
date];//获得当前的时间

    NSURL *url = [NSURL
URLWithString:@"http://pic14.nipic.com/20110522/7411759_164157418126_2.jpg"];

    NSDate *end = [NSDate
date];//获得当前的时间

    NSLog(@"%f",[end
timeIntervalSinceDate:start]);

    

   
//2.根据url地址把图片的二进制数据下载到本地

    NSData *data = [NSData
dataWithContentsOfURL:url];

  

    //3.转换为图片

    UIImage *image = [UIImage
imageWithData:data];

    

    self.imageView.image = image;

}

//计算代码段的执行时间(2)

-(void)test2

{

    //1.确定url地址

    CFTimeInterval start =
CFAbsoluteTimeGetCurrent(); //2000

    

    NSURL *url = [NSURL
URLWithString:@"http://pic14.nipic.com/20110522/7411759_164157418126_2.jpg"];

    CFTimeInterval end =
CFAbsoluteTimeGetCurrent(); //2000

    NSLog(@"%f",end - start);

    

   
//2.根据url地址把图片的二进制数据下载到本地

    NSData *data = [NSData
dataWithContentsOfURL:url];

    

    //3.转换为图片

    UIImage *image = [UIImage
imageWithData:data];

    

    self.imageView.image = image;

}

//在子线程中下载图片

-(void)download

{

    NSLog(@"%@",[NSThread
currentThread]);

    

    //1.确定url地址

    NSURL *url = [NSURL
URLWithString:@"http://pic14.nipic.com/20110522/7411759_164157418126_2.jpg"];

    

   
//2.根据url地址把图片的二进制数据下载到本地

    NSData *data = [NSData
dataWithContentsOfURL:url];

    

    //3.转换为图片

    UIImage *image = [UIImage
imageWithData:data];

    

    //4.回到主线程刷新UI

    /*

     第三个参数:YES --NO

     */

    

//    [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES];

    

   
//第二种方式回到主线程

//    [self performSelector:@selector(showImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];

    [self.imageView
performSelectorOnMainThread:@selector(setImage:)
withObject:image waitUntilDone:YES];

}

//-(void)showImage:(UIImage *)image

//{

//    NSLog(@"%@--刷新UI",[NSThread currentThread]);

//    self.imageView.image = image;

//}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: