【问题标题】:NSPredicate nested or subquery?NSPredicate 嵌套或子查询?
【发布时间】:2013-11-02 15:51:26
【问题描述】:

我正在尝试编写一个 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];

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

【问题讨论】:

    标签: ios subquery nspredicate


    【解决方案1】:
    Recipe *recipe = [theRecipeArray objectAtIndex:0];
    

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-25
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-16
      • 1970-01-01
      相关资源
      最近更新 更多