【问题标题】:Save images to NSMutableDictionary and than to plist将图像保存到 NSMutableDictionary 而不是 plist
【发布时间】:2014-08-26 11:18:11
【问题描述】:

我需要保存从服务器获取的图像

[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:URL]]];

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

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

然后,我需要将它保存到光盘。对我来说有两种解决方案,但没有一种可行... :-(。第一个是将其保存为 NSUserDefaults,第二个是将其保存到 iPhone 的根目录下的 .plist 文件。我想使用那个 .plist,所以我做了:

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

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

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

【问题讨论】:

  • "但是当我尝试 NSLog 时,它不起作用。" - 什么 不工作? 怎么做?这和 Xcode 有什么关系?
  • 不工作意味着它没有记录任何东西......还有xCode,因为我在xCode中编码? :-) 如有错误请见谅...

标签: ios image dictionary plist


【解决方案1】:

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

【讨论】:

  • 我尝试将其保存到 NSData,而不是将其保存到 plist,但它不起作用,NSLog 只是说“(null)”...... :-(
【解决方案2】:

您不能直接存储UIImage 对象。将他们的NSData 放入NSDictionary 以便能够保存它们。下载的NSData 或通过UIImagePNGRepresentation(image) 创建新的

来自NSDictionarywriteToFile:atomically:的文档

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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多