将UIimageView中的图像保存到Core Data

时间:2014-04-29 21:59:07

标签: ios objective-c uiimageview

我有一个“按钮”将图像从相机胶卷加载到imageView,这非常有效。 现在我将图像保存在imageView我的数据库中。

我有4个“文本字段”,这没有问题。当我添加代码以保存“图像”时,应用程序崩溃。

在我的.h文件中:

@property (weak, nonatomic) IBOutlet UIImageView *pictureData;

代表UIImage

我的.m文件:

- (IBAction)save:(id)sender {
    NSManagedObjectContext *context = [self managedObjectContext];

    if (self.device) {
        // Update existing device
        [self.device setValue:self.nameTextField.text forKey:@"name"];
        [self.device setValue:self.versionTextField.text forKey:@"version"];
        [self.device setValue:self.companyTextField.text forKey:@"company"];
         [self.device setValue:self.adresse.text forKey:@"adresse"];
        [self.device setValue:self.pictureData forKey:@"picture"];



    } else {
        // Create a new device
        NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context];
        [newDevice setValue:self.nameTextField.text forKey:@"name"];
        [newDevice setValue:self.versionTextField.text forKey:@"version"];
        [newDevice setValue:self.companyTextField.text forKey:@"company"];
        [newDevice setValue:self.adresse.text forKey:@"adresse"];
        [newDevice setValue:self.pictureData forKey:@"picture"];


    }

    NSError *error = nil;
    // Save the object to persistent store
    if (![context save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }

    [self dismissViewControllerAnimated:YES completion:nil];
}

xcdatamodeld(核心数据)我有图片类型二进制数据集! 错误在哪里?

3 个答案:

答案 0 :(得分:1)

您应该保存其UIImageView属性,而不是保存imageThis stack overflow question显示了如何在CoreData中保存和检索UIImage

1)存储图像:

NSData* data = [NSData dataWithData:UIImagePNGRepresentation(yourUIImage)];
// save 'data' to core data

2)加载图片:

// retrieve data from core data as per usual, stored in 'data'
UIImage* image = [UIImage imageWithData:data];

答案 1 :(得分:0)

这是问题,

[self.device setValue:self.pictureData forKey:@"picture"];

UIImageView是一个对象而不是二进制数据,替换以下语句

[self.device setValue:UIImagePNGRepresentation(self.pictureData.image) forKey:@"picture"];

编辑:

要回头,

[self.pictureData setImage:[UIImage imageWithData:[self.device valueForKey:@"picture"]]];

答案 2 :(得分:0)

您应避免将图像存储在RAM中,因此图像也不应存储在Core Data中。将映像写入磁盘,并将文件名存储在数据库中。

使用[UIImage imageWithContentsOfFile:]从磁盘读取文件 - 这将完美地处理低内存情况。