iOS多线程之02网络图片下载

  • iOS多线程之02网络图片下载_第1张图片
    Snip20170115_3.png
  • 一个小的实现效果:
  • pics.gif

代码并没有写的很细致,只是大致的写出了思路,如下

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    IMApp *app = self.Apps[indexPath.row];
    
    UIImage *image = self.icons[app.name];
    
    if (image == nil) {
        
        NSString *fileName = [NSString stringWithFormat:@"%@.png",app.name];
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *final = [path stringByAppendingPathComponent:fileName];
        image = [UIImage imageWithContentsOfFile:final];
        
        if (image == nil) {
            //下载图片并展示操作
            [[[NSOperationQueue alloc] init] addOperationWithBlock:^{
                NSLog(@"下载中。。。。。");
                NSURL *url = [NSURL URLWithString:app.icon];
                NSData *data = [NSData dataWithContentsOfURL:url];
                
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                    UIImage *image = [UIImage imageWithData:data];
                    cell.imageView.image = image;
                    [self.tableView reloadData];
                    [self.icons setObject:image forKey:app.name];
                    
                    NSString *fileName = [NSString stringWithFormat:@"%@.png",app.name];
                    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                    NSString *final = [path stringByAppendingPathComponent:fileName];
                    
                    [data writeToFile:final atomically:NO];
                }];
            }];
        }else{
            NSLog(@"下载缓存");
            [self.icons setObject:image forKey:app.name];
        }
    }else{
        NSLog(@"内存中有");
    }
    cell.imageView.image = image;
    cell.textLabel.text = app.name;
    
    return cell;
}

你可能感兴趣的:(iOS多线程之02网络图片下载)