I am having trouble saving a photo into core data. I am trying to save it as an attribute set to ‘Transformable’ in an Entity. I have seen various discussions on this on SO and the consensus seems to be that in iOS5 and above, I don’t need to use a coder as UIImage now conforms to NSCoding. I am getting an error when I try and save Core Data. Please see below the code I am using to save the photo…
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
UIImage *originalImage, *editedImage, *imageToSave;
// Handle a still image capture
if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo) {
editedImage = (UIImage *) [info objectForKey:UIImagePickerControllerEditedImage];
originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
if (editedImage) {
imageToSave = editedImage;
} else {
imageToSave = originalImage;
}
// Convert image to Data for entry into Core Data
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(imageToSave)];
// Add image to Core Data
myEntity.attribute = imageData;
NSError *error = nil;
if (![managedObjectContext save:&error]) {
NSLog(@"Error when saving core data");
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
[[picker parentViewController] dismissModalViewControllerAnimated: YES];
[picker release];
}
I have done this many times. Change the storage type from transformable to Binary Data and you should be fine.
You also want to keep a couple of things in mind. If the image is small (1MB or less), there should be no issue storing it in your main entity. If it is larger, you should have the image stored in an entity by itself for performance reasons. If the image is very large, you may want to consider storing it off in the documents directory like anonymous suggests above.