CoreData多对多关系 [英] CoreData many-to-many relationship

查看:347
本文介绍了CoreData多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在CoreData中使用多对多关系?
例如:

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

我有2个实体 - Recipes&成分

I have 2 entities - Recipes & Ingredients

CoreData将其链接成食谱< - >成分。
现在我需要为食谱中的每个Ingredient添加属性Count。我如何做?

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

感谢

推荐答案

关心对象图一致性维护为你。因此,如果使用SQLite存储,Core Data会自动为您创建多对多关系的中间连接表。在你的情况下,你应该明确地创建一个中间(join)实体。中间实体的一个优点是,您还可以使用它向
关系添加更多信息,例如IngredientInfo实体可能包含Count列。所以你的模型应该看起来像:食谱< - >>成分信息< < - >成分

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.

更新:和计数

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

或快速访问某些食谱中的所有食材使用KVC

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

NSSet* ingredients = [recipe valueForKeyPath:@"ingredientInfo.ingredient"];

这篇关于CoreData多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆