Thor Larson
Thor Larson

Reputation: 43

Search for the index of a Core Data array that contains a certain date attribute

I have been looking around everywhere online and can't seem to get a solid answer. If I have an event with multiple attributes stored in Core Data in an array and I can display all of these individual events in a tableView. Lets say one of the attributes is a date. Is there away to search for all of the events that contain a certain date and display only those in the tableView? I was thinking of using NSPredicate from what I am seeing online but I am not familiar with this. Maybe somehow find the index of the event that contains that date and only display that index? Any ideas?

Upvotes: 0

Views: 63

Answers (1)

Alain T.
Alain T.

Reputation: 42143

Table views are designed to implement a one to one relationship with the underlying array of data. The usual approach is to use a fetchRequest to only get the data you want to display ( I personally like to have all my requests pre-defined in the data model so I can keep track of how data is accessed).
But, if your array of managed record must contain more elements than what you want to display, you should consider basing your tableView datasource responses on an intermediate array that only contains (or refers to) the objects you want to show.

For example:

 let allEvents:[EventRecord] = GetAllEvents()
 var filteredEvents:[EventRecord] = allEvents.filter({ $0.eventDate.isEqualToDate(dateToDisplay) })

and use filteredEvents as your underlying store for your datasource.

This will make it easy to dynamically change the filtering conditions and reload the tableview without having to go back to the database for each filter change.

Upvotes: 1

Related Questions