4
votes

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

2
Check the type of object stored in objects. My guess is they are instances of Events. - Mike D
Does error get set, or is it still nil? - adpalumbo
Can you try to print objects. There is a chance that your object is fault. - shannoga
"one element that is nil" doesn't make any sense, because NSArray cannot contain nil values. What are you actually getting? - Tom Harrington
Good questions! NSLogging of [objects class] gives "_PFArray", error gives "(null)" and objects gives "<Events: 0x9074D50> (entity: Events; id: ... , data: <fault>)" Strange that the other properties are not listed. Yes, in the debugger I see the "[0]" element but there's nothing there. - ScottyB

2 Answers

8
votes

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!

0
votes

Please call willAccessValueForKey: before accessing @"data"

[objects[0] willAccessValueForKey:@"data"];
NSMutableDictionary *data = objects[0][@"data"];
[objects[0] didAccessValueForKey:@"data"];