Reputation: 4833
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];
}
Upvotes: 2
Views: 812
Reputation: 5782
I agree to Joseph's answer. But looking at Apple's recommendation for storing image if your image is(Courtesy - Marcus S. Zarra's answer here):
From your code what I see is you are trying to save image taken from camera to Core Data. We know images taken from Phone/iPad camera are approx 2.5 Mbs nowadays. So it is quite possible that you will get performance issues. So I would advice you to store image in a document directory and save it's path as NSString
in your entity. It will be a more efficient way.
Upvotes: 2
Reputation: 3278
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.
Upvotes: 1