1

I am getting an image from photo library and saving it to core data and then showing it to an image view. This is correctly working. But when i run project again the image is not showing on my image view.

This is code for getting image from photo library

   -(void)imagePickerController:(UIImagePickerController *)picker   didFinishPickingMediaWithInfo:(NSDictionary *)info


{

 [picker dismissModalViewControllerAnimated:YES];



   UIImage *img= [info objectForKey:@"UIImagePickerControllerOriginalImage"];


NSManagedObjectContext *context=[self managedObjectContext];

NSManagedObject *newContact=[[NSManagedObject alloc] initWithEntity:[NSEntityDescription entityForName:@"Contacts" inManagedObjectContext:context] insertIntoManagedObjectContext:context];
//newContact = [NSEntityDescription insertNewObjectForEntityForName:@"Images" inManagedObjectContext:context];

NSData *data=UIImageJPEGRepresentation(img,0.0);
[newContact setValue:data forKey:@"image"];
[self fetchData];

}

This is the code of fetchData() method.

 -(void)fetchData
{
 NSManagedObjectContext *context=[self managedObjectContext];

    NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Contacts"
                               inManagedObjectContext:context]];
NSError * error = nil;
NSArray * objects = [context executeFetchRequest:request error:&error];
if ([objects count] > 0) {
    NSManagedObject *managedObject = objects[0];
    data1 = [managedObject valueForKey:@"image"];
    image2 = [[UIImage alloc]initWithData:data1];
    _imageView.image=image2;
}

}

This is my viewDidLoad()

- (void)viewDidLoad
{
[super viewDidLoad];
[self fetchData];

// Do any additional setup after loading the view.
}

4 Answers4

5

First you should save image path (not uiimage) to Core Data and then get the path from Core Data and load image to your imageView by this path.

And use Magical Record (https://github.com/magicalpanda/MagicalRecord) for managing Core Data and you will have no problem with it at all.

0

You modify your coredata context by setting an entity but you don't save the modifications. It is for this reason that it is not saved when you run your project again.

To fix it you must save your NSManagedObjectContext context after modifications by simply using save method.

So, at the end of your fetchData method, try to make :

[context save:nil];

(You can pass a NSError in parameter to get errors during save.)

0

To save:

[newChannelToCoreData setValue:UIImagePNGRepresentation(_currentChannelImage) forKey:@"image"];

To fetch:

_currentChannelImage = [UIImage imageWithData:[lastChannel valueForKey:@"image"]];
James Zaghini
  • 3,895
  • 4
  • 45
  • 61
0

do this after all modifications on coredata

NSError *error = nil;
if (![context save:&error]) {
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}
thorb65
  • 2,696
  • 2
  • 27
  • 37