2013-11-02 150 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"];