【问题标题】:Saving pictures in IPhone apps在 iPhone 应用程序中保存图片
【发布时间】:2012-02-07 09:53:34
【问题描述】:

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

-(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 这样存储好吗?

【问题讨论】:

    标签: ios uiimage nskeyedarchiver


    【解决方案1】:

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

    【讨论】:

    • 用户可以添加jpeg或png,我们不知道。如果我的图像是 JPEG 格式,它可以正常工作吗?或者我应该如何实现 encodeWithCoder?
    • PNG 是无损的,因此它可以用于保存 JPEG 而不会造成任何质量损失,但图像会比它们需要的大。我知道你可以使用 UIImageJpegRepresentation 保存的文件类型。
    • 我现在无法检查。因为模拟器中的画廊是空的。你为什么?我应该在哪里保存图片以便在模拟器中使用它们?
    • 只需将图像拖到模拟器窗口/手机上,它就会在 Mobile Safari 中打开。然后按住它,直到出现“保存图像”操作表。保存它,它将出现在您的照片库中。
    【解决方案2】:

    问题中实现的编码器和解码器都可以

    【讨论】:

    • 你在 iOS 4.3 中试过了吗?看起来 Apple 可能在 iOS5 中为 UIImage 添加了 NSCoding 支持,但在 iOS4 中不存在,所以我敢打赌,如果你在 4.3 模拟器中运行它会崩溃,在这种情况下,你仍然需要使用我的解决方案,除非你的目标只是 5.0 以上。
    • 在 iOS5 上试用会发生什么?
    • 你确定使用相同的键名来加载和保存?顺便说一句,您的解决方案是否适用于 IOS4?
    猜你喜欢
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多