CoreData多对多关系

编程入门 行业动态 更新时间:2024-10-28 07:25:35
本文介绍了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多对多关系

本文发布于:2023-10-23 13:28:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1520949.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:关系   CoreData

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!