views:

45

answers:

2

Hi everyone,

I have an entity which has relationships with other entities. Let say we have: user->menu->meal

My problem is that some of the users don't have a menu. So when I try to check: user.menu.meal == rice I get an error (path not found...)!

Thank you for your help!

A: 

Add a nil check on the relationship then...

if (user.menu != nil && user.menu.meal != nil)

Or even better, define a helper method that will return the meal if it's present...

mealForUser:(User*)someUser {
     if (user.menu != nil && user.menu.meal != nil)
     return user.menu.meal;
}
mmccomb
The problem is that I have some to many relationships and can't check each of the menus and meals... don't you have a better solution to implement IN the NSPredicate?
ncohen
You can perform similar checks in your NSPredicate. If you have a FetchRequest for the entity user then you can specify a NSPredicate as follows...predicate = [NSPredicate predicateWithFormat:@"(menu != nil) AND (menu.meal != nil)"];
mmccomb
Ok but let say some of my users have menus and some of these menus have meals. How would you do with these 'one to many' relationships?
ncohen
To deal with one-to-many relationships you can use....[NSPredicate predicateWithFormat:@"(menu != nil) AND (menu.meals@count > 0)"]
mmccomb
That is a lot of dancing just to use dot syntax when a simple KVC call will work.
Marcus S. Zarra
A: 

First, you can check this in code as:

if (![user valueForKeyPath:@"menu.meal"]) {
 //User does not have a menu or a meal
}

Inside of your predicate it would look the same:

[NSPredicate predicateWithFormat:@"user.menu.meal == nil"]

In either case, because nil is handled gracefully in Objective-C you will get the right answer.

Marcus S. Zarra