如何在 NSCoder 中编码 UIImage
我有一个“User”对象,其中包含“UIImage”类的属性。
如何将图像与其他属性一起编码并将其保存在 NSUserDefaults
中?
我的理解是我只能编码 NSString
?
例如,当前在我的代码中,我在编码/解码实现中添加 avatar_url
(字符串)。如何将 url 转换为 UIImage
然后对其进行编码?
- (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"];
}
}
I have a 'User' object that contains a property of 'UIImage' class.
How do I encode the image together with the other properties and save it in NSUserDefaults
?
My understanding is that I can only encode NSString
s?
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"];
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
更新
正如评论中指出的,
UIImage
符合NSCoding
,因此您可以直接对其进行编码,如下所示:这样做的优点是它(应该)存储所有图像的属性,包括
scale
和imageOrientation
,如果未将它们设置为默认值,则保留这些属性可能非常重要。但是,它确实存在一些您应该注意的风险。如果图像是直接从您的应用程序包加载的,则存档将包含图像名称,但不图像数据。如果存档确实包含图像数据,则它将采用 PNG 格式,而您可能更喜欢 JPEG 格式,具体取决于您要编码的图像类型。
原始
使用
UIImagePNGRepresentation
或UIImageJPEGRepresentation
将UIImage
转换为NSData
,然后对NSData
进行编码code>:稍后解码图像:
UPDATE
As pointed out in the comments,
UIImage
conforms toNSCoding
, so you can just encode it directly, like this:This has the advantage that it (should) store all the properties of the image, including
scale
andimageOrientation
, which may be pretty important to preserve if they're not set to the defaults.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.
ORIGINAL
Use
UIImagePNGRepresentation
orUIImageJPEGRepresentation
to convert theUIImage
to anNSData
, then encode theNSData
:To decode the image later: