CoreData many-to-many relationship

后端 未结 1 437
长情又很酷
长情又很酷 2021-01-06 19:46

How to operate with many-to-many relationship in CoreData? For example:

I have 2 entities - Recipes & Ingredients

CoreData links them like Recipes <&

相关标签:
1条回答
  • 2021-01-06 20:19

    Core Data takes care of the object graph consistency maintenance for you. So if you use a SQLite store, Core Data automatically creates the intermediate join table for you for many-to-many relationships. In your case, you should explicitly create an intermediate (“join”) entity. An advantage of the intermediate entity is that you can also use it to add more information to the relationship—for example a “IngredientInfo” entity might include 'Count' column. So you model should look like: Recipe <-->> IngredientInfo <<--> Ingredient.

    If you find something unclear here I'll update the answer.

    Update: Access ingredients and count

        for (IngredientInfo* ingredientInfo in recipe.ingredientInfos) {
            Ingredient* ingredient = ingredientInfo.ingredient;
            NSNumber* count = ingredientInfo.count;
        }
    

    Or to quick access to all ingredients in certain Recipe use KVC

    NSSet* ingredients = [recipe valueForKeyPath:@"ingredientInfo.ingredient"];
    
    0 讨论(0)
提交回复
热议问题