2012-04-25 154 views
6

我是一位与核心数据相关的新手。任何人都可以帮助我提供适当的步骤/教程,展示如何将图像保存到核心数据及其还原。我能够存储字符串数据,但我的应用程序在尝试保存图像时崩溃。 为了节省:将图像保存为核心数据

DataEvent *event = (DataEvent *)[NSEntityDescription insertNewObjectForEntityForName:@"DataEvent" 
                  inManagedObjectContext:managedObjectContext]; 
NSURL *url2 = [NSURL URLWithString:@"xxxxxxxxxxxxxxx SOME URL xxxxxxxxxxxx"]; 

NSData *data = [[NSData alloc] initWithContentsOfURL:url2]; 
imageSave=[[UIImage alloc]initWithData:data]; 
NSData * imageData = UIImageJPEGRepresentation(imageSave, 100.0);  
[event setValue:self.imageSave forKey:@"pictureData"]; 

对于retrival:

DataEvent *event = (DataEvent *)[eventsArray objectAtIndex:indexPath.row]; 
UIImage *image = [UIImage imageWithData:[event valueForKey:@"pictureData"]]; 
UIImageView *imageViewMainBackGround = [[UIImageView alloc] 
CGRect rect3=CGRectMake(0,2,100.0,100.0); 
imageViewMainBackGround.frame = rect3; 
[cell.contentView addSubview:imageViewMainBackGround]; 
[imageViewMainBackGround release]; 
+0

什么是你的模型文件 “pictureData” 数据类型? – 2012-04-25 11:19:00

+0

其二进制数据类型 – 2012-04-25 12:49:10

+0

“用于打开商店的模型与用于创建商店的模型不兼容”您会在哪里得到此错误? – 2012-04-25 13:13:15

回答

0

你必须设置你的管理对象到NSData对象的pictureData值(在你的情况为imageData),而不是imageSave对象,这是一个UIImage

如果它没有必要
1

不要更改分辨率..

NSData * imageData = UIImageJPEGRepresentation(imageSave, 0.0); 

//并更改以下行

[event setValue:imageData forKey:@"pictureData"]; 

See the store and Retrieve image from core data tutorial with sample code.

希望,这将帮助你..

+0

嗨,这样做后,我得到错误:原因=“用于打开商店的模型与用于创建商店的模型不兼容”; – 2012-04-25 08:02:08

+0

在保存或检索..? – Nit 2012-04-25 08:04:11

+0

保存图片数据 – 2012-04-25 10:58:03

2

error: reason = "The model used to open the store is incompatible with the one used to create the store"

解决方案:

删除模拟器生成项目,从清洁产品标签,现在运行项目。

9

为了节省:

NSData *imageData = UIImagePNGRepresentation(myUIImage); 

[newManagedObject setValue:imageData forKey:@"imageKey"]; 

而且 以检索图片:

NSManagedObject *selectedObject = [[self fetchedResultsController] objectAtIndexPath:indexPath]; 
UIImage *image = [UIImage imageWithData:[selectedObject valueForKey:@"imageKey"]]; 
[[newCustomer yourImageView] setImage:image]; 

改变格式