IOS 多图下载程序缓存处理

多图下载程序缓存处理

缓存处理有

​ 1.内存缓存(把下载好的image保存到字典中,程序关闭就会删除)

​ 2.磁盘缓存(把图片的NSData数据保存到caches文件上,程序关闭不会删除这里的数据)

​ 3.操作缓存(把下载的操作保存到字典里,避免出现重复下载的情况)

多图片下载(多线程处理)

//先判断缓存里是否已经下载好这张图片
    UIImage *image = [self.icondict objectForKey:status.user.name];
    if(image){
        self.iconView.image = image;
    }else{
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        NSString *filename = [user.profile_image_url lastPathComponent];
        //拼接caches缓存的全路径
        NSString *fullPath = [caches stringByAppendingString:filename];
        
        //检查磁盘缓存里有没有数据
        NSData *iconData = [NSData dataWithContentsOfFile:fullPath];
        if(iconData){
            //磁盘缓存中已存在数据
            self.iconView.image = [UIImage imageWithData:iconData];
        }else{
            //磁盘缓存中不存在数据
            NSString *imageUrl = user.profile_image_url;
            //先判断缓存中是否有下载操作
            NSBlockOperation *operation = [self.operationDict objectForKey:[imageUrl lastPathComponent]];
            if (operation) {
                return;
            }else{
                //实现异步下载图片
                    operation = [NSBlockOperation blockOperationWithBlock:^{
                    NSData *imagedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
                    UIImage *image = [UIImage imageWithData:imagedata];
                    //线程间通信(imageView设置image要在主线程中进行)
                    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                        self.iconView.image = image;
                    }];
                    //把图片保存到内存缓存里面
                    [self.icondict setObject:image forKey:status.user.name];
                    
                    //写数据到沙盒里面
                    [imagedata writeToFile:fullPath atomically:YES];
                    
                    //删除下载操作缓存
                    [self.operationDict removeObjectForKey:[imageUrl lastPathComponent]];
                }];
                //添加操作到缓存中
                [_operationDict setObject:operation forKey:[imageUrl lastPathComponent]];
                //把线程加入到队列中
                [self.queue addOperation:operation];
            }
            }
      
      //在主控制器中做到释放内存
      //释放缓存
-(void)didReceiveMemoryWarning
{
    photosView *view = [[photosView alloc] init];
    [view.photosDict removeAllObjects];
    [view.cachesA removeAllObjects];
    [view.photosA removeAllObjects];
    [view.queue cancelAllOperations];
    
    vbcell *cell = [[vbcell alloc] init];
    [cell.icondict removeAllObjects];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值