2013-03-09 194 views
0

從以下源文件,我嘗試加載圖像並保存到核心數據,也顯示在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

請注意,大多數人都持謹慎態度(最好)約下載.zip文件。如果您發佈一些相關的代碼,並且突出顯示可能給您帶來麻煩的部分,我們就會更容易理解該問題。 – 2013-03-09 19:32:32

+0

請確定問題中的相關源代碼部分,並將其包含在您的問題中。 – 2013-03-09 19:47:03

+1

我真的建議將圖像保存到磁盤並在核心數據中保存*路徑* – Hyperbole 2013-03-09 21:08:21

回答

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