您的位置:首页 > 移动开发 > IOS开发

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

2015-05-10 11:16 141 查看
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];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: