如何在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多对多关系
发布评论