How to encode a UIImage in an `NSCoder`

2020-02-26 00:33发布

问题:

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 NSStrings?

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"];
    }
}

回答1:

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"];

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.

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 or UIImageJPEGRepresentation to convert the UIImage to an NSData, then encode the NSData:

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

To decode the image later:

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