Saturday, October 17, 2009

Unexpected nil values in Core Data

I had a head scratching few minutes the other day.

Using Core Data for the first time on the iPhone and had set a default value for a string field on an object that was accessed via a relationship from another entity.

Every time a queried it via KeyPath I would get a nil value. The solution would have been obvious had I not been in the mind set that I was doing something wrong wrt to Core Data.

Turns out I was not instantiating the sub object when I created the main object I was working from.

Tasting *tasting = (Tasting *)newManagedObject;

NSEntityDescription *wineEntity = [NSEntityDescription entityForName:@"Wine" inManagedObjectContext:managedObjectContext];

tasting.wine = [[Wine alloc] initWithEntity:wineEntity insertIntoManagedObjectContext:managedObjectContext];

Adding that last line was the trick. Duh.

No comments:

Post a Comment