CoreData many-to-many relationship

痞子三分冷 提交于 2020-01-11 03:41:05

问题


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

I have 2 entities - Recipes & Ingredients

CoreData links them like Recipes <<-->> Ingredients. Now I need to add attribute "Count" for every Ingredient in Recipe. How can I do it?

Thanks


回答1:


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"];


来源:https://stackoverflow.com/questions/14973660/coredata-many-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!