使用UIImages将NSMutableArray保存到NSUserDefaults

时间:2011-11-09 10:46:11

标签: objective-c uiimage nsuserdefaults nscoding

我试图保存NSMutableArray,它包含五个UIImages到NSUserDefaults并且不起作用。我收到了警告

-[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value '(
    "UIImage: 0x4c76570,
    "UIImage: 0x4c76570",
    "UIImage: 0x4c76570",
    "UIImage: 0x4c76570",
    "UIImage: 0x4c76570"
)' of class '__NSArrayM'.

好像我需要将我的数据存档到NSData中。但是我如何使UIImage符合NSCoding?我应该首先将我的图像转换为NSData还是有更简单的方法?

1 个答案:

答案 0 :(得分:4)

是的,您需要使用UIImagePNGRepresentationUIImageJPEGRepresentation函数以所需格式检索图像的二进制数据,然后您可以将其序列化为NSArray。< / p>

一个例子:

UIImage *someImage = ...;
NSData *someImageData = UIImagePNGRepresentation(someImage);
[yourArray addObject:someImageData];

//...

[[NSUserDefaults standardUserDefaults] setObject:yourArray forKey:@"images"];