NSThread执行下载图片操作

- (IBAction)downloadImageByNSThread:(id)sender {
    //1.NSThead对象
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(downloadImage) object:nil];
    //2.执行下载逻辑
    //3.启动子线程
    [thread start];
}

- (void)downloadImage {
    //NSSting -> NSURL -> NSData -> UIImage
    NSString *imageStr = @"http://www.egouz.com/uploadfile/2015/0305/20150305103626911.jpg";
    NSURL *imageUrl = [NSURL URLWithString:imageStr];
    //如下方法是耗时的操作
    NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
    UIImage *image = [UIImage imageWithData:imageData];
    /*由子线程回到主线程,赋值给imageView
      主线程执行任务优先级高于子线程任务
     */
    //子线程回到主线程方式一(理解)
    [self performSelectorOnMainThread:@selector(returnMainThread:) withObject:image waitUntilDone:YES];
    
    NSLog(@"35345");
}

- (void)returnMainThread:(UIImage *)image {
    NSLog(@"赋值:%@", [NSThread currentThread]);
    self.imageView.image = image;
}

你可能感兴趣的:(NSThread执行下载图片操作)