I have a simple has many relationship between 2 entities in Core Data:
Team <------->> Games
When I insert a new game managed object into a context, I need to query some properties of the team entity, at the model layer. However, when I use awakeFromInsert
the relationship has not been set yet, so team
is nil
.
// game.m
- awakeFromInsert
{
[super awakeFromInsert];
if ([self team] isActive] {
//.... set game properties
}
}
Is there a way to build the relationship before calling insert and setting the relationship after:
Game *newGame = [NSEntityDescription insertNewObjectForEntityForName:@"Game"
inManagedObjectContext:managedObjectContext];
[newGame setTeam:team];
In rails I would use @team.games.build
but this doesn't seem possible in Core Data.
I suspect you will either need a custom method such as + (Game *)insertGameForTeam:(Team *)team
and do your team
checks there or else handle the relationship conditions in - (void)willSave
if you need to keep it at the model level.
Using only the default logic, the object doesn't exist until you finish inserting it and you can't associate it with another object until it exists.