NSImage to NSData, then to UIImage

Anoop Vaidya picture Anoop Vaidya · Apr 24, 2014 · Viewed 16k times · Source

I am creating a plist from my OSX app that contains some images. I am writing the image by :

[NSKeyedArchiver archivedDataWithRootObject:self.someImage]

Then I am using this plist file as a template for iOS app, but here I can't convert the file to UIImage and neither to NSImage(as this is only for OSX).

I am getting this error:

* Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '* -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (NSImage)'

Please suggest me a way to perform the above.

Answer

Josh Freeman picture Josh Freeman · Apr 27, 2014

OS X:
Instead of using NSKeyedArchiver to convert an NSImage to NSData, use NSImage's TIFFRepresentation method:

NSData *imageData = [self.someImage TIFFRepresentation];
// save imageData to file

iOS:
Read the image data from the file, then convert it to a UIImage using UIImage's +imageWithData: convenience constructor:

NSData *imageData = ...; // load imageData from file
UIImage *image = [UIImage imageWithData: imageData];