NSInvalidArgumentException when accessing core data object

73 Views Asked by At

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Contacts length]:

I'm fetching image from coredata and obvious the format of image is BYTE, so I'm converting it into image. I'm using the following code:

NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Contacts"
                               inManagedObjectContext:context]];

NSError * error = nil;
NSArray * objects = [context executeFetchRequest:request error:&error];
NSData *data1= objects[0];

UIImage *image2 = [[UIImage alloc]initWithData:data1];

What to do?

2

There are 2 best solutions below

0
Shekhu On

you can use the following

NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity1 = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:context];
[fetchRequest setEntity:entity1];
NSArray * array = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
 NSData * dataBytes = [[array objectAtIndex:0] imgPng];
image = [UIImage imageWithData:dataBytes];
1
Matthias Bauch On

[context executeFetchRequest:request error:&error]; returns an array with instances of NSManagedObject or subclasses of NSManagedObject. You tell the compiler that the array contains instances of NSData, which is not the case. Hence the unknown selector method.

If we assume you save the image data in an attribute called imageData your code would look like this:

NSArray * objects = [context executeFetchRequest:request error:&error];
NSAssert(objects, @"Can't fetch: %@", error);
if ([objects count] > 0) {
    NSManagedObject *object = objects[0];
    NSData *data = [object valueForKey:@"imageData"];
}