Frage

I'm trying to add images into core data and load it when needed. I'm currently adding the NSImage to the core data as follows:

Thumbnail *testEntity = (Thumbnail *)[NSEntityDescription insertNewObjectForEntityForName:@"Thumbnail" inManagedObjectContext:self.managedObjectContext];
NSImage *image = rangeImageView.image;
testEntity.fileName = @"test";
testEntity.image = image;
NSError *error;
[self.managedObjectContext save:&error];

Thumbnail is the entity name and I have two attributes under the Thumbnail entity - fileName(NSString) and image (id - transformable).

I'm trying to retreive them as below:

NSManagedObjectContext *context = [self managedObjectContext];

NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *imageEntity = [NSEntityDescription entityForName:@"Thumbnail" inManagedObjectContext:[context valueForKey:@"image"]];

[fetchRequest setEntity:imageEntity];

NSError *error;

NSArray * array = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

if (array == nil) {

    NSLog(@"Testing: No results found");

}else {



   _coreDataImageView.image = [array objectAtIndex:0];
}

I end up with this error:

     [<NSManagedObjectContext 0x103979f60> valueForUndefinedKey:]: this class is not key value coding-compliant for the key image.

The image is added but couldn't retrieve.
Any idea on how to go about with this? Am I doing it right ?

War es hilfreich?

Lösung

The error is in this line

NSEntityDescription *imageEntity = [NSEntityDescription entityForName:@"Thumbnail"
          inManagedObjectContext:[context valueForKey:@"image"]];

You cannot apply valueForKey:@"image" to a managed object context. You have to apply it to the fetched objects (or use the image property of the fetched object).

Note also that executeFetchRequest: returns nil only if an error occurs. If no entities are found, it returns an empty array.

NSEntityDescription *imageEntity = [NSEntityDescription entityForName:@"Thumbnail" inManagedObjectContext:context];
[fetchRequest setEntity:imageEntity];

NSError *error;
NSArray * array = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (array == nil) {
    NSLog(@"Testing: Fetch error: %@", error);
} else if ([array count] == 0) {
    NSLog(@"Testing: No results found");
}else {
   Thumbnail *testEntity = [array objectAtIndex:0];
   NSImage *image = testEntity.image;
   _coreDataImageView.image = image;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top