Codebrah
Codebrah

Reputation: 11

NSPredicate filter for less than OR nil

I want NSPredicate to give me back results for a keyPath that is either nil... or less than a given date. I'm using the NSPredicate for core data.

These are working correctly...

let endDatePredicate = NSPredicate(format: "%K > %@", #keyPath(RepeatingTask.endDate), date as NSDate)
let endDatePredicate = NSPredicate(format: "%K == nil", #keyPath(RepeatingTask.endDate), date as NSDate)

But I can't get these to work correctly with an OR operator...

let endDatePredicate = NSPredicate(format: "%K > %@ || %K == nil", #keyPath(RepeatingTask.endDate), date as NSDate)
let endDatePredicate = NSPredicate(format: "%K > %@ OR %K == nil", #keyPath(RepeatingTask.endDate), date as NSDate)
let endDatePredicate = NSPredicate(format: "(%K > %@) || (%K == nil)", #keyPath(RepeatingTask.endDate), date as NSDate)

Upvotes: 0

Views: 304

Answers (1)

LoVo
LoVo

Reputation: 2073

You can use NSCompoundPredicate. For example:

let first = NSPredicate(format: "%K > %@", #keyPath(RepeatingTask.endDate), date as NSDate)
let second = NSPredicate(format: "%K == nil", #keyPath(RepeatingTask.endDate), date as NSDate)
let predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [first, second])

Upvotes: 2

Related Questions