如何在`NSCoder`中编码UIImage [英] How to encode a UIImage in an `NSCoder`

查看:128
本文介绍了如何在`NSCoder`中编码UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个'User'对象,其中包含'UIImage'类的属性。

I have a 'User' object that contains a property of 'UIImage' class.

如何将图像与其他属性一起编码并保存在 NSUserDefaults

How do I encode the image together with the other properties and save it in NSUserDefaults?

我的理解是我只能编码 NSString s?

My understanding is that I can only encode NSStrings?

例如,我目前在我的代码中添加 avatar_url (字符串)编码/解码实现。如何将网址转换为 UIImage 然后对其进行编码?

For example, currently in my code, I am adding the avatar_url (string) in the encode/decode implementation. How can I convert the url to UIImage and then encode it?

- (void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeObject:self.uid forKey:@"uid"];
    [encoder encodeObject:self.avatar_url forKey:@"avatar_url"];
}

- (id)initWithCoder:(NSCoder *)decoder
{
    self = [super init];
    if( self != nil ){
         self.uid = [decoder decodeObjectForKey:@"uid"];
         self.avatar_url = [decoder decodeObjectForKey:@"avatar_url"];
    }
}


推荐答案

更新



正如评论中所指出的, UIImage 符合 NSCoding ,所以你可以直接编码,如下所示:

UPDATE

As pointed out in the comments, UIImage conforms to NSCoding, so you can just encode it directly, like this:

[encoder encodeObject:image forKey:@"image"];

这样做的好处是它(应该)存储图像的所有属性,包括 scale imageOrientation ,如果它们没有设置为默认值,这可能非常重要。

This has the advantage that it (should) store all the properties of the image, including scale and imageOrientation, which may be pretty important to preserve if they're not set to the defaults.

然而,它确实存在一些您应该注意的风险。如果图像是直接从您的应用包中加载的,则存档将包含图像名称,但图像数据。如果存档包含图像数据,它将采用PNG格式,而您可能更喜欢JPEG格式,具体取决于您编码的图像类型。

However, it does have some risks you should be aware of. If the image was loaded directly from your app bundle, the archive will contain the image name, but not the image data. And if the archive does contain the image data, it will be in PNG format, while you might prefer JPEG format depending on the kind of image you're encoding.

使用 UIImagePNGRepresentation UIImageJPEGRepresentation 转换 UIImage NSData ,然后编码 NSData

Use UIImagePNGRepresentation or UIImageJPEGRepresentation to convert the UIImage to an NSData, then encode the NSData:

[encoder encodeObject:UIImagePNGRepresentation(self.image) forKey:@"image"];

稍后解码图像:

self.image = [UIImage imageWithData:[decoder decodeObjectForKey:@"image"]];

这篇关于如何在`NSCoder`中编码UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆