how to create a many to many relationships with core data? Swift, xcode

元气小坏坏 提交于 2019-12-20 05:36:15

问题


I have 2 entities.

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).

I am not sure how to do this.

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?


回答1:


Person attribute as array of string names of books -- very bad idea!

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 }

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



来源:https://stackoverflow.com/questions/36110240/how-to-create-a-many-to-many-relationships-with-core-data-swift-xcode

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