在 Core Data 上保存一个 UIImage

Save a UIImage on Core Data

如何在核心数据中保存 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];



}

使用您的代码:

-(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];



} 

由于UIImage符合NSCoding,您需要做的就是将属性类型从"binary"更改为"transformable"。然后你可以直接给属性赋一个UIImage,Core Data会自动调用它的NSCoding方法实现二进制数据的转换。

在您的代码中,您只需添加:

[object setValue:image forKey:@"name of your image attribute here"];