I have a core data entity with a property called eventTimes
.
This eventTimes
is a string property that may be empty or contain values like the four examples below.
9:00, 10:00, 14:00, 16:00
13:00
11:00, 12:00, 15:00, 18:00, 21:00, 23:00, 0:00
14:00, 16:00, 19:00
Now I need to filter that using NSPredicate
based on a time value. It needs to be NSPredicate
because it will be used with CoreData's NSFetchController and SwiftUI.
Example: give me the entries that contain 14:00.
I need to use something like
NSPredicate(format: "eventTimes IN %@", array )
But in my case is the opposite, that is eventTimes
is the array and the object is the other element.
Something like
NSPredicate(format: "%@ IN eventTimes", oneTime )
But if I do that, it crashes.
Any way to do this?
eventTimes
isn’t an array even if you want it to be. It’s a string and your predicate is crashing because of that fact.
You could use a compound predicate to compose a query against the string like:
NSPredicate(format: "eventTimes CONTAINS %@", timeString )
and form an array to be passed to
NSCompoundPredicate(orPredicateWithSubpredicates:)
But that gets rapidly messy so you’re better to do it right and form an EventTime
entity with a many-to-one relationship to Event
(Or whatever you’re calling the relevant entity).
This approach allows you to form complex time based searches e.g “Find me all events that start before 12:00” without using magic string formatting too.