Out of the box, UIImage doesn’t support the NSCoding protocol which means it won’t automatically serialize if you stuff these in a dictionary or object and archive (using NSKeyedArchiver for example). The easy solution is to convert this into an NSData object which does support the protocol:
//convert from PNG to NSData, other method available for JPG NSData *imageData = UIImagePNGRepresentation(imageToArchive); [self.currentItem setValue:imageData forKey:@"image"]; //after the archived object is unarchived, you can retrieve the image like this NSData *imageData = [currentItem valueForKey:@"image"]; if(imageData){ UIImage *image = [UIImage imageWithData:imageData]; }
Without doing this, and trying to archive a UIImage will just result in:
-[UIImage encodeWithCoder:]: unrecognized selector sent to instance
Pretty simple. The key is the helper method UIImagePNGRepresentation found in the UIKit Function Reference.
Thanks for this, helped a lot, just how I like it short and sweet and bang on the money.
Brilliant.
Perfect. Just what I needed, right when I needed it.
L.