2015-03-31 182 views
1

我从照片库中获取图像并将其保存到核心数据,然后将其显示到图像视图。这是正确的工作。但是当我再次运行项目时,图像没有显示在我的图像视图中。无法从coredata获取数据

这是从照片库

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

}

获取图像代码这是fetchData()方法的代码。

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

} 

这是我的viewDidLoad()

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

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

回答

0

您可以通过设置一个实体修改coredata背景,但你不保存修改。正因如此,当您再次运行您的项目时,它不会被保存。

要修复它,您必须通过简单地使用save方法在修改后保存您的NSManagedObjectContext上下文。

所以,在你的fetchData方法的末尾,尽量让:

[context save:nil]; 

(您可以在参数传递一个NSError保存过程中出现错误。)

+0

哦,我在做非常愚蠢的错误做了这一切之后的修改。现在完成了。谢谢 – 2015-03-31 10:34:41

5

首先,你应该保存图像路径(而不是uiimage)到Core Data,然后从Core Data获取路径并通过此路径将图像加载到imageView。

并使用魔法记录(https://github.com/magicalpanda/MagicalRecord)来管理核心数据,你完全没有问题。

0

为了节省:

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

要提取:

_currentChannelImage = [UIImage imageWithData:[lastChannel valueForKey:@"image"]]; 
0

上coredata

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