robola robola - 1 year ago 108
iOS Question

core data relationship retrieve using key

I have the following data model relationship (attributes in parenthesis)

Day (date) ----------->> Event (date, name)

There is a one to many relationship from Day to Event. There is no inverse relationship (i.e the Event entity doesn't have a reference to Day)

The Events are created first and saved. The Day gets created later.

Is there a way when retrieving the Day entity to have core data also go and retrieve every Event that has the same date as the date of that Day? I have searched some other questions, but all of them include manually setting the Events when the Day is created.

Answer Source

You query into CoreData with NSFetchRequest, which can only query one specific entity type (hence the initWithEntityName(_:) initializer). If you do not have a relationship set between the two entities, you cannot retrieve both of them with a single NSFetchRequest instance (you may be able to use the same NSPredicate, given that you have a date attribute on both).

Having said that, as the answers to the other questions probably indicate, if you have a relationship set you can set the property relationshipKeyPathsForPrefetching on the NSFetchRequest entity to whatever your relationship key is to fetch the entities for a relationship when you fetch the initial entities. Assuming your goal is to avoid multiple trips to the database, you may also want to consider setting returnsObjectsAsFaults to false (only do this if you have a relatively small number of objects).