将图像保存到NSMutableDictionary而不是plist

时间:2014-07-05 11:10:18

标签: ios image dictionary plist

我需要保存使用

从服务器获取的图像
[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:URL]]];

对于NSMutableDictionary - 它对我来说没问题,我这样做(它是在每个获取的图像的循环中):

[self.imagesDict setObject:image forKey:[[xmlArray objectAtIndex:x] objectForKey:@"_img"]];

而且,我需要将它保存到光盘。我有两个解决方案,但没有人工作...... :-(。第一个是保存它做NSUserDefaults,第二个是将它保存到.plist文件到iPhone的根目录。我想用那个.plist,所以我做的:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pathLD = [documentsDirectory stringByAppendingPathComponent:@"imagesDict"];

[self.imagesDict writeToFile:pathLD atomically:YES];

但是当我尝试NSLog时,它不起作用。然而,当我将一些字符串而不是图像保存到字典时,它就像一个魅力。所以有人可以帮助我,但我做错了什么?非常感谢!

2 个答案:

答案 0 :(得分:1)

您无法直接存储UIImage个对象。将他们的NSData放在NSDictionary内以便能够保存它们。已下载的NSData或通过UIImagePNGRepresentation(image)

创建新的NSDictionary

来自writeToFile:atomically:的{​​{1}}

的Dokumentation

This method recursively validates that all the contained objects are property list objects (instances of NSData, NSDate, NSNumber, NSString, NSArray, or NSDictionary) before writing out the file, and returns NO if all the objects are not property list objects, since the resultant file would not be a valid property list.

答案 1 :(得分:1)

我可以看到两个问题。首先,您应该使用.plist作为字典的文件扩展名。但更重要的是,您正在尝试保存包含无法序列化为plist的对象(UIImage)的字典。 Plists仅支持有限数量的对象类型,例如NSNumber,NSData,NSString。在NSDictionary类引用中查看writeToFile:atomically:description。它列出了允许的内容。如果要将图像保存到plist,则必须将其自身序列化为NSData。不过,我认为这不是一个好主意,因为NSData表示可能比原始图像大很多。我认为你最好找另一种方法来做这件事。