This code should save am uiimage to core data. The image is stored in it’s own entity and liked to another entity (relationship)
NSEntityDescription *imageEntity = [ NSEntityDescription insertNewObjectForEntityForName:kImage inManagedObjectContext:self.context];
[imageEntity setValue:self.image forKey:kPicture];
[newPerson setValue:imageEntity forKey:kPicture];
NSError *error;
if (![self.context save:&error]) {
NSLog(@"Whoops, couldn't save new associate: %@", [error localizedDescription]);
}
Here I try to get it back , to put it in an uiimageview on a custom cell
Person *crt = [self.fetchController objectAtIndexPath:indexPath];
cell.name.text = crt.name;
Image *img = crt.picture;
cell.image.image = img.picture;
This only works when the picture is first added … after restarting the app the image does not show again.. Why is that? It’s set as a transformable attribute
You can add an
UIImageonly as binary data. So what you need to do it set your entity’s attribute type toBinary Data, and the use theCoreGraphics'methodUIImagePNGRepresentation(UIImage *image), which returnsNSDataand save it this way. And if you want to extract it from the database, you get theNSDataand create an image with[UIimage imageWithData:(NSData *data)]method.But I think the best implementation is to store only the local path to the image in your database, but the actual file is stored in a folder in your app’s Documents folder… just a suggestion.