在iPhone应用程序中保存图片

时间:2012-02-07 09:53:34

标签: ios uiimage nskeyedarchiver

我有一个包含对象数组的应用程序,我已存档和取消存档

-(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会以这种方式存储好吗?

2 个答案:

答案 0 :(得分: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以包含正常的super / nil检查,这是最佳实践。

请注意,您可能希望使用self = [self init]self = [super initWithCoder:aDecoder]代替self = [super init],具体取决于您的超类是什么以及您的init是否进行了任何其他设置。

答案 1 :(得分:0)

编码器和解码器,在问题中实现是好的