1

我正在尝试编写一个 NSPredicate 来返回给定食谱的所有成分。我的实体Recipe有一个recipeName,所以我想指定recipeName,然后Recipe与IngredientList有关系,它与Ingredients有一对多的关系。我想获取指定食谱的所有成分。成分名称。

这是我的数据模型。 截屏 我已经尝试过这样的事情,但它不会编译,我确信我的 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];

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

4

1 回答 1

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

是你找到的食谱。相关成分很简单

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

(allObjects只需要得到 anNSArray而不是 a NSSet。) 然后你通过 Key-Value Coding 得到一个包含所有名称的数组:

NSArray *ingredientNames = [ingredients valueForKey:@"ingredientName"];
于 2013-11-02T16:18:09.707 回答