如何在核心数据中保存由UIImagePickerController
挑选的照片。在我的数据模型中,我将其设置为类型Binary Data
并允许它存储在外部
到目前为止,这是我的代码。
- (IBAction)addPhoto:(id)sender {
_picker = [[UIImagePickerController alloc]init];
_picker.delegate = self;
_picker.allowsEditing = NO;
_picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:_picker animated:YES completion:nil];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [delegate managedObjectContext];
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context];
[self dismissViewControllerAnimated:YES completion:nil];
[self.imageView reloadInputViews];
}
答案 0 :(得分:0)
使用您的代码:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [delegate managedObjectContext];
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context];
// One option:
NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
// Second option.
// NSData *imagenData2 = UIImagePNGRepresentation(image);
object.theNameOfYourBinaryDataAttribute = imageData;
[context save:nil]; // Or handling error.
[self dismissViewControllerAnimated:YES completion:nil];
[self.imageView reloadInputViews];
}
答案 1 :(得分:0)
由于UIImage
符合NSCoding
,您需要做的就是将属性类型从“二进制”更改为“可转换”。然后,您可以直接为该属性分配UIImage
,Core Data将自动在其上调用NSCoding
方法以转换为二进制数据和从二进制数据转换。
在您的代码中,您只需添加以下内容:
[object setValue:image forKey:@"name of your image attribute here"];