如何与核心数据创建多对多关系? Swift,xcode [英] how to create a many to many relationships with core data? Swift, xcode

查看:153
本文介绍了如何与核心数据创建多对多关系? Swift,xcode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个实体。

实体1 - 人
实体2 - 书

entity 1 - People entity 2 - books

人物实体有一个属性,它是他们最喜欢的书的字符串名称数组。

People entity has a property which is an array of string names of their favorite books.

我需要创建一个关系,以某种方式将人物的喜爱的书映射到相应的书实体对象。

I need to create a relationship that somehow maps the favorite book of a person to the corresponding book entity object(s).

我不知道该怎么做。

到目前为止,我开始在人们的核心数据模型中创建关系,方法是将目标设置为books,然后通过将目标设置为people。

So far I have started by creating a relationship in core data model for people by setting destination to "books" and then for the books entity creating a relationship by setting destination to "people".

我没有看到或了解这将如何自动挑选每个人最喜欢的图书...在一天结束时,他们都是独立的对象。

I don't see or understand how this will automatically pick out each of the person's favorite books...at the end of the day they are both seperate objects. How will the people class know that for a specific people instance that this, this and this book are that person's favorite?

推荐答案

您需要与Book实体的一对多关系。而已。

You need a to-many relationship with the Book entity. That's it.

 Person <------------>> Book

然后,为特定人获取一系列图书标题:

Then, to get an array of book titles for a particular person:

(person.books as! Set<Book>).map { $0.title }

这个人可以有一个额外的一对一关系(例如 favoriteBook )。

The person can have an additional to-one relationship (e.g. called favoriteBook) to one of the books.

这篇关于如何与核心数据创建多对多关系? Swift,xcode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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