1
votes

Case:
I am working on an app using Core Data with 2 different entities Note and Sleep. During a day there may be added instances of these entities multiple times.

Note stores timestamp (Date), a note (String) and a few other irrelevant attributes. Used to take daily notes. Sleep stores timeStart (Date) and timeEnd (Date) - Used to track the user's sleep.

Issue
I want to fetch all the entries of both Entities Note + Sleep and group them by timestampand timeEnd; so it can be displayed in a table view with a cell/row for each date.

The sleep data will be used to calculate the total hours of sleep (e.g. if the user sleeps twice a day)

Some days there might be only Notes and other days only Sleep.

How would I go about this? I hope it makes sense; otherwise please let me know.

1
Do you want to group them by DAY rather than Date, bearing in mind that Core Data Date will be down to seconds of perhaps even milliseconds and so you may have some difficulty matching Note and Sleep records. It might be easier to create a relationship between Note and Sleep(s) where there is one Note per DAY and none-or-more Sleeps per DAY. Then Note can have a transient attribute that calculates the hours of sleep from the related Sleep records - Duncan Groenewald
Thanks for your input Duncan; I can see I might have to rethink the way I structure my app. I will need some time to figure out how I want to do it. - Jakob Halskov

1 Answers

2
votes

A Core Data fetch request can only fetch objects of one particular entity (and optionally the sub-entities). The same is true for a fetched results controller.

Therefore to display Note and Sleep entities together in a table view, you have the following options:

  • use a single entity that holds all attributes, or
  • make Note and Sleep inherit from a common parent entity, or
  • create a third entity Entry with the timestamp attribute and to-one relationships to Note and Sleep.

Note that in the second case Core Data would also store all objects in a single table containing all attributes.

In either case, you can sort the objects on the timestamp, or group them into sections using the sectionNameKeyPath parameter of the fetched results controller.

The only alternative would be to fetch the objects separately and merge them, but then you lose all advantages of the fetched results controller, like automatic change tracking.