Search code examples
iosswiftcore-datansfetchedresultscontrollernsmanagedobject

How to add additional objects with fetch result controller fetched objects list?


I have an entity called “Event“ which has s start and end date properties. I have to show the list of events by grouping them by date in UI. I am using NSFetchedResultsController to fetch and list the events.

Let's assume an event has start date today and end date tomorrow, here I need to show this event on two different dates in UI but I will have only one entry in the database.

I really don’t want to create multiple entries for an event and also I wish to use fetch result controller as it reduces lot manual calculation. Is there any way to solve this?


Solution

  • NSFetchedResultsController does a good job of matching NSManagedObjects to indexPaths for a tableView. However, the mapping is one to one, so any given Event can only appear once in the indexPaths. To achieve what you want, you would need to create a new entity, say EventDate, with a to-many relationship from Event to EventDate. Define a string attribute which reflects whether the date is at the start or end of the event. Then base your FRC on the EventDate entity. Although each EventDate will appear only once, multiple EventDates could relate to a single Event. The inverse relationship from EventDate to Event will enable you to access the details of a single Event from multiple EventDates.