Reputation: 1954
I write an array of Contacts objects to file like this
[NSKeyedArchiver archiveRootObject:listOfContactsToLay toFile:[self fPath]];
Contact class implements the corresponding protocol,
but it has an UIImage field and it's not gonna encode or decode throwing an encode exception. how should I write UIImage
field?
Upvotes: 1
Views: 2627
Reputation: 1310
Short solution
- (id)initWithCoder:(NSCoder *)decoder
{
if ((self = [super init]))
{
NSData *data = [decoder decodeObjectForKey:@"UIImage"];
self = [self initWithData:data];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder
{
NSData *data = UIImagePNGRepresentation(self);
[encoder encodeObject:data forKey:@"UIImage"];
}
@end
source : http://iphonedevelopment.blogspot.com/2009/03/uiimage-and-nscoding.html
Upvotes: 3
Reputation: 331
UIImage does not conform to encodeWithCoder, so it will throw the exception every time. You can save the image directly to user defaults, but the best way is to simply save the image out to the documents directory and then save the path of image file. If the images are pre-rendered, it's obviously very easy. If they are generated on the fly (such as with image contexts, etc), then you can cast them to NSData:
NSData *imageData = UIImageJPEGRepresentation(myImage, CGFloat compressionQuality);
[imageData writeToFile:pathYouCreate atomically:YES];
Then you save out the path as a property in your NSKeyedArchiver.
Upvotes: 0
Reputation: 3294
You can get an NSData
object containing either a PNG or JPEG representation of the image data using the UIImagePNGRepresentation
and UIImageJPEGRepresentation
functions.
Upvotes: 2