iOS开发-缓存图片到沙盒 总结

iOS开发-缓存图片到沙盒  总结




今天写一个demo, 涉及图片缓存操作。

也就是, 把通过照相机拍下来的图片, 保存到应用中。

因为还涉及了其他数据, 包括图片像素大小, 关键点等等等...

所以很自然的想到了存储在.plist文件中, 再把plist文件写入沙盒。


于是乎..第一次写的时候, 直接这样:

NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString * namePath = [documentsDirectory stringByAppendingPathComponent:@"gift_info.plist"];
    
    NSMutableArray *myArr = [[NSMutableArray alloc] initWithContentsOfFile:namePath];
    NSMutableDictionary *info = [[NSMutableDictionary alloc]init];
    
    [info setObject:myImage forKey:@"img"];
    [myArr addObject:info];
    [myArr writeToFile:namePath atomically:YES];

这里的myImage就是我要存储的UIImage类型的数据。

但是结果呢。很明显, 这样是存储不了的(也就是不会生成对应的plist文件)。因为plist文件不能存储UIImage类型的数据。

犯了这个低级错误...真是蛋疼。


然后接下去是第二版。

    [info setObject:UIImagePNGRepresentation(myImage)forKey:@"img"];

这里修改了图片的存储类型:转为NSData格式。

然后在要使用图片的时候, 使用如下语句:

    UIImage *myImg = [UIImage imageWithData:[myArr objectAtIndex:i]objectForKey:@"img"];

这种办法, 理论上行得通。

但是, 转为data导致plist文件过大,加载缓慢,影响其他数据的展示。所以也不是一个好办法。


下面介绍我最后使用的一个办法。

先把图片直接存储到沙盒中。 然后plist文件中记录图片的路径。然后要使用图片的时候通过访问plist文件获取图片路径来调用。

下面是使用示例:

一。图片存储到沙盒中

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_%d.png", myI]];   // 保存文件的名称
        [UIImagePNGRepresentation(myImage)writeToFile: filePath    atomically:YES];

二。在plist中保存路径
NSMutableDictionary *info = [[NSMutableDictionary alloc]init];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_%d.png", conut_]];   // 保存文件的名称

[info setObject:filePath forKey:@"img"];
[specialArr addObject:info];

三。使用图片
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_%d.png", (int)current]];   // 保存文件的名称
UIImage *img = [UIImage imageWithContentsOfFile:filePath];



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值