2012-02-07 81 views
0

我有对象数组的应用程序,这是我存档,未归档保存图片在IPhone应用程式

-(id)initWithCoder:(NSCoder *)aDecoder{ 
    title = [aDecoder decodeObjectForKey:@"Title"]; 
    image = [aDecoder decodeObjectForKey:@"Image"]; 
    return self; 
} 

-(void)encodeWithCoder:(NSCoder *)aCoder{ 
    [aCoder encodeObject:title forKey:@"Title"]; 
    [aCoder encodeObject:image forKey:@"Image"]; 
} 

UIImage店好这样?

回答

0

编码器和解码器,这是问题的落实都OK

+1

你在iOS 4.3中试过吗?看起来Apple似乎已经在iOS5中为UIImage添加了NSCoding支持,但它在iOS4中并不存在,所以我敢打赌它会在4.3模拟器中运行时崩溃,在这种情况下,您仍然需要使用我的解决方案,除非你只向上瞄准5.0。 – 2012-02-11 16:08:54

+0

很抱歉,您的解决方案在ios5上无效 – 2012-02-11 16:20:41

+1

当您在iOS5上尝试时会发生什么? – 2012-02-11 16:36:37

4

不,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是否执行任何其他设置。

+0

用户可以添加JPEG或PNG,我们不知道。如果我的图像是JPEG格式,它会工作吗?或者我应该如何实现encodeWithCoder? – 2012-02-08 05:32:30

+1

PNG是无损的,所以它可以用来保存JPEG,没有任何质量损失,但图像会比他们需要的更大。我知道你可以使用UIImageJpegRepresentation来保存文件类型。 – 2012-02-08 07:53:07

+1

你为什么不接受?它不适合你吗? – 2012-02-08 10:11:32

相关问题