2013-11-02 46 views
1

我想写一个NSPredicate,将返回给定食谱的所有成分。我的实体食谱有一个recipeName,所以我想指定recipeName,然后食谱与IngredientList有一种关系,它与Ingredients有多对多的关系。我想抓取指定配方的所有Ingredient.ingredientNames。NSPredicate嵌套或子查询?

这是我的数据模型。 screenshot http://i44.tinypic.com/148gf8k.png 我已经试过这样的事情,但它不会编译,我相信有什么毛病我的for循环:

NSManagedObjectContext *context = [[self appDelegate] managedObjectContext]; 

// Construct a fetch request 
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Recipe" 
              inManagedObjectContext:context]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"recipeName==%@", targetRecipe.recipeName]; 

[fetchRequest setPredicate:predicate]; 
[fetchRequest setEntity:entity]; 
NSError *error = nil; 
self.theRecipeArray = [context executeFetchRequest:fetchRequest error:&error]; 

NSLog(@"The recipe you found was %@", [theRecipeArray objectAtIndex:0]); 

//Query the one Recipe for all ingredients? 
for (ingredient.IngredientName * Ingredient.ingredientName in theRecipeArray) 
    [ingredientsArray addObject: ingredientName]; 

会给我正确的配方,但后来我怎么抓住它ingredientList和它的所有成分?

回答

1
Recipe *recipe = [theRecipeArray objectAtIndex:0]; 

是您找到的配方。相关成分只是

NSArray *ingredients = [recipe.ingredientList.ingredient allObjects]; 

allObjects仅需要得到一个NSArray而不是NSSet的。) 然后你得到一个数组通过键 - 值编码的所有名称:

NSArray *ingredientNames = [ingredients valueForKey:@"ingredientName"];