Question

I have a "Button" to load an image from the Camera Roll to an imageView, this works perfect. Now I will save the image in the imageView my Database.

I have 4 "Text fields" , this works without issues. When I add the code to save the "image", the app crashes.

In the .h file I have :

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

for the UIImage.

my .m file:

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

in xcdatamodeld(core Data) I have picture as Type Binary Data set! Where is the error?

Was it helpful?

Solution 2

Here is the problem,

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

UIImageView is a object not binary data, replace the following statement

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

Edit:

To retrive,

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

OTHER TIPS

Rather than saving the UIImageView, you should save its image property. This stack overflow question shows how to save and retrieve a UIImage to/from CoreData:

1) Store the image:

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

2) Load image:

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

You should avoid storing images in RAM and therefore images also should not be stored in Core Data. Write the image to the disk, and store the filename in your database.

Use [UIImage imageWithContentsOfFile:] to read the file from the disk - this will handle low memory situations perfectly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top