将图像保存到Core Data

时间:2013-03-09 19:25:46

标签: ios core-data uiimage

从以下源文件中,我尝试加载图像并保存到Core Data并在imageView中显示但它不起作用 你能帮我解决一下吗?

- (IBAction)save:(id)sender
{
    NSLog(@"Telling the AddTrackingTVC Delegate that save was tapped on the     AddTrackingTVC");

    [self.delegate theSaveButtonOnTheAddPlantNoteTVCWasTapped:self];

    MyPlant *myTracking = [NSEntityDescription insertNewObjectForEntityForName:@"MyPlant" inManagedObjectContext:self.managedObjectContext];

    myTracking.name = nameTextField.text;
    myTracking.detail = detailTextField.text;
    myTracking.createdDate = [NSDate date];
    //myTracking.photo = [NSData ];
    [self.managedObjectContext save:nil]; // write data to database
    [self.delegate theSaveButtonOnTheAddPlantNoteTVCWasTapped:self];
}




- (IBAction)takePicture:(id)sender {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    // If our device has a camera, we want to take a picture, otherwise, we // just pick from photo library
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera]; }
    else {
    [imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary]; }
    // This line of code will generate a warning right now, ignore it
    [imagePicker setDelegate:self];
    // Place image picker on the screen
    [self presentViewController:imagePicker animated:YES completion:nil];
}


-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    self.currentEntry.photo = UIImageJPEGRepresentation([info   objectForKey:UIImagePickerControllerOriginalImage], 1.0);
    [self dismissViewControllerAnimated:YES completion:nil];

}

那么我与这些功能有什么关系,使它能够将图像保存到核心数据?

Download source files

1 个答案:

答案 0 :(得分:5)

我就是这样做的:

NSURL * imageURL = [NSURL URLWithString:@"http://www.website.com/picture.png"];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage * image = [UIImage imageWithData:imageData];
NSData *savedImageData = UIImagePNGRepresentation(image);
[coreDataObject setValue:savedImageData forKey:@"image"];

当你想要展示它时:

imageView.image = [UIImage imageWithData:[coreDataObject valueForKey:@"image"]];