我无法将照片保存到核心数据中。我正在尝试将其保存为实体中设置为“可转换”的属性。我已经看到关于 SO 的各种讨论,并且共识似乎是在 iOS5 及更高版本中,我不需要使用编码器,因为 UIImage 现在符合 NSCoding。尝试保存 Core Data 时出现错误。请参阅下面我用来保存照片的代码...
- (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];
}