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

  • 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;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,268评论 25 709
  • WebSocket-Swift Starscream的使用 WebSocket 是 HTML5 一种新的协议。它实...
    香橙柚子阅读 24,397评论 8 183
  • 突然想起了小时候,小学的时候爸爸还没有回来,我小学比较早下课,发现灯管没亮,就自己搬梯子检查启辉、灯管解决了问题。...
    慕苏苏阅读 1,774评论 0 0
  • 十点钟写了两篇,一下子,就快十二点了。 有些困了。明天去买票,上广州。回家也已经有二十几天,有开心,有不开心。不过...
    心情小屋阅读 536评论 0 0
  • 篇章:三起两落一场大病 虽然看的创业类人物传记书籍不多,但是Elon的起落和那些年看的偶像剧中情节如此雷同:白手起...
    谷音sp阅读 3,627评论 0 0

友情链接更多精彩内容