不,UIImage不符合NSCoding协议。
要保存图像,请使用UIImageJPEGRepresentation(image, quality)
或UIImagePNGRepresentation(image)
将其转换为NSData,然后您可以将NSData对象保存在编码器中,因为它符合NSCoding。
像这样:
-(id)initWithCoder:(NSCoder *)aDecoder{
if ((self = [super init])){
title = [aDecoder decodeObjectForKey:@"Title"];
image = [UIImage imageWithData:[aDecoder decodeObjectForKey:@"ImageData"]];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:title forKey:@"Title"];
[aCoder encodeObject:UIImagePNGRepresentation(image) forKey:@"ImageData"];
}
PS,我假设你正在使用ARC?如果不是,则需要在initWithCoder方法中保留这些值,因为decodeObjectForKey:
会返回一个自动释放对象。我还重写了你的initWithCoder以包含正常的超/无检查,这是最佳实践。
请注意,您可能希望使用self = [self init]
或self = [super initWithCoder:aDecoder]
而不是self = [super init]
,这取决于您的超类是什么以及您的init是否执行任何其他设置。
你在iOS 4.3中试过吗?看起来Apple似乎已经在iOS5中为UIImage添加了NSCoding支持,但它在iOS4中并不存在,所以我敢打赌它会在4.3模拟器中运行时崩溃,在这种情况下,您仍然需要使用我的解决方案,除非你只向上瞄准5.0。 – 2012-02-11 16:08:54
很抱歉,您的解决方案在ios5上无效 – 2012-02-11 16:20:41
当您在iOS5上尝试时会发生什么? – 2012-02-11 16:36:37