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"];
}
}
UPDATE
As pointed out in the comments,
UIImageconforms 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
scaleandimageOrientation, 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
UIImagePNGRepresentationorUIImageJPEGRepresentationto convert theUIImageto anNSData, then encode theNSData:To decode the image later: