NSPredicate嵌套还是子查询?

时间:2013-11-02 15:51:26

标签: ios subquery nspredicate

我正在尝试写一个NSPredicate,它将返回给定食谱的所有成分。我的实体Recipe有一个recipeName,所以我想指定recipeName,然后Recipe与IngredientList有一个关系,它与Ingredients有很多关系。我想抓住指定食谱的所有Ingredient.ingredientNames。

这是我的数据模型。 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];

会给我正确的食谱,但是我如何抓住它的成分列表及其所有成分?

1 个答案:

答案 0 :(得分:1)

Recipe *recipe = [theRecipeArray objectAtIndex:0];

是您找到的食谱。相关的成分只是

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

allObjects只需获得NSArray而不是NSSet。) 然后通过键值编码得到一个包含所有名称的数组:

NSArray *ingredientNames = [ingredients valueForKey:@"ingredientName"];
相关问题