I have a very simple CoreData model that has 1 entity and 2 attributes.
This code works fine:
.onChange(of: searchText) { _, text in
evnts.nsPredicate = text.isEmpty ? nil :NSPredicate(format: "eventName CONTAINS %@ " , text )
but I'd like to also search with the same text string for my second attribute (which is a Date). I believe an OR is appropriate for two conditions (find either one). See attempted code below:
evnts.nsPredicate = text.isEmpty ? nil : NSPredicate(format: "(eventName CONTAINS %@) OR (dueDate CONTAINS %i) " , text )
This crashes immediately %@ does the same. Is there a way to accomplish this?
How is SwiftUI not an option below?
NSPredicate(format: "eventDate CONTAINS %i " , text )
This won't work if eventDate
is of Date
type and text
is a string. You will need to convert text
to a Date
object, and then do something like this:
let eventDatePredicate = NSPredicate(format: "eventDate == %@", dateFromText as NSDate)
let predicate = NSCompoundPredicate(ordPredicateWithSubpredicates: [eventNamepredicate, eventDatePredicate])
How to converting a string to a date is covered in DateFormatter.
Best,
——
Ziqiao Chen
Worldwide Developer Relations.