Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Core Data executeFetchRequest is returning empty object

I'm using Core Data to store an entity which includes a transformable NSDictionary attribute. I can see an object in .SQLite file after I store it, so I think (?) I'm good there. However, when I try to retrieve the entire entity, I get an NSArray with one element [0] that is nil and (of course) crashes when I try to access any attribute.

HVBAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];

NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Events" inManagedObjectContext:context];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entityDesc];

NSError *error;
NSArray *objects = [context executeFetchRequest:fetchRequest error:&error];

// [objects count] = 1 but objects[0] = nil

// and the following line crashes of course
NSMutableDictionary *data = objects[0][@"data"];

Any idea what I'm doing wrong? Thanks!

(Note that I have set up an Events class with the NSDictionary property and other properties as well.)

Here's how I set up the entity:

enter image description here

Events.h:

enter image description here

Events.m:

enter image description here

like image 211
ScottyB Avatar asked Feb 14 '23 03:02

ScottyB


1 Answers

I figured out what was going on:

First, the reason that 'objects' had one row, but appeared "empty" was because that is the default behavior. Values will not be retrieved until you specifically ask for them, unless you change that by sending a setReturnsObjectsAsFaults message:

[fetchRequest setReturnsObjectsAsFaults:NO];

Note that NSLogging the object without this produced "data: ".

Second, and most important, 'objects' is NOT an NSArray of NSDictionarys or NSMutableDictionarys. So while I can replace [objects objectAtIndex:0]" with "objects[0], I can not replace [objects[0] valueForKey:@"created"] with [objects[0][@"created"]. That's what caused the crash.

Hope this helps someone!

like image 172
ScottyB Avatar answered Feb 16 '23 03:02

ScottyB