美文网首页
SDWebImage(内部实现原理)

SDWebImage(内部实现原理)

作者: Jack_zz | 来源:发表于2015-10-17 01:25 被阅读206次

(1)涉及知识点

     01 字典转模型
     02 存储数据到沙盒,从沙盒中加载数据
     03 占位图片的设置(cell的刷新问题)
     04 如何进行内存缓存(使用NSDictionary)
     **注意**:使用一个字典,可以临时保存数据,但是会出现内存问题(内存警告),如果不是SDWebImage,我们需要手动清除内存;
     05 在程序开发过程中的一些容错处理
     //注意:在图片还在下载过程中,系统又重新下载,我们需要定义一个操作字典,来保存我们已经加入的操作,避免反复操作!
     06 如何刷新tableView的指定行(解决数据错乱问题)
     //注意:在cell还没有加载图片完成的时候就已经被循环使用到下面去了会导致我们的cell出现数据错乱的问题,所以我们使用指定行刷星,避免出现这样的问题;
     07 NSOperation以及线程间通信相关知识
Snip20151016_1.png
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *path = NSTemporaryDirectory();
    NSLog(@"%@",path);
    static NSString *ID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    LPJModel *model = self.models[indexPath.row];
    cell.detailTextLabel.text = model.download;
    cell.textLabel.text = model.name;
    //cell.image
    //先从字典中找
    UIImage *cacheImage = self.cacheImages[model.icon];
    if (!cacheImage) {
        //如果没有就从沙盒中找
        NSData *data = [NSData dataWithContentsOfFile:[model.icon cacheDir]];
        UIImage *image = [UIImage imageWithData:data];
        image = nil;
        if (image) {
            cell.imageView.image = image;
        }else
        {
            //添加占位图
            cell.imageView.image = [UIImage imageNamed:@"1"];
            //看看是否存在下载操作
            NSOperation *downloadOp = self.operations[model.icon];
            if (!downloadOp) {
                NSOperationQueue *queue = [[NSOperationQueue alloc]init];
                NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
                    NSURL *url = [NSURL URLWithString:model.icon];
                    NSData *data1 = [NSData dataWithContentsOfURL:url];
                    UIImage *image1 = [UIImage imageWithData:data1];
                    [self.operations removeObjectForKey:model.icon];
                    //                cell.imageView.image = image1;
                    //刷新一行
                    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:NO];
                        //将操作从字典中移除
                        
                    }];
                    [self.cacheImages setValue:image1 forKey:model.icon];
                    //将图片存在沙盒中
                    [data1 writeToFile:[model.icon cacheDir] atomically:YES];
                }];
                [queue addOperation:op];
                //将操作加入字典
                [self.operations setObject:op forKey:model.icon];
//                NSLog(@"%@",self.operations);
                }else
                    {
                    }
            
            }
        }else
            {
        cell.imageView.image = cacheImage;
    }
    
    return cell;
}

相关文章

网友评论

      本文标题:SDWebImage(内部实现原理)

      本文链接:https://www.haomeiwen.com/subject/qdracttx.html