0

I need to set up my NSPredicate base on actual value stored in CoreDate.

Assuming we have a CoreData entity: "Graduate". we want to fetch graduate whose graduation date is earlier than Date1 if his/her graduation date is not null. Otherwise, I want to check if his/her birthday is earlier than Date2.

The predicate would look like this:

"if graduationDate != null graduationDate < %@ else birthday < %@"

So I actually have two predicate. The second one should only come into effect if the field which first predicate wants to check is null.

My thoughts:

  1. I can process this in my APP instead of CoreData, but just wonder is there a way to use only one NSPredicate to sort it out.

  2. Some posts mentioned that NSPredicate is an equivalent to SQL Where Clause, which makes sense to me. And I think what I need here is going to beyond what Where Clause is capable of.

My question is not about how to filter fetch result using NSPredicate. It's about how to setup NSpredicate using a flow control like if else clause

Todanley
  • 468
  • 3
  • 12
  • 1
    https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/FetchingObjects.html Scroll down to "**Filtering Results**" . The question has also been asked on SO several times you can search before posting a new one. You can also add NSCompoundPredicate https://developer.apple.com/reference/foundation/nscompoundpredicate for multiple predicates as you want. –  Mar 20 '17 at 01:04
  • If NSPredicate and NSCompoundPredicate are "basic usage" , can you please explain what the advanced usage of Core Data fetching is and what you are asking for, for us less educated basic users? –  Mar 20 '17 at 01:54
  • Possible duplicate of [iOS CoreData NSPredicate to query multiple properties at once](http://stackoverflow.com/questions/10611362/ios-coredata-nspredicate-to-query-multiple-properties-at-once) –  Mar 20 '17 at 02:42

1 Answers1

2

You can use NSCompoundPredicate to combine smaller predicates.

    let graduates = NSPredicate.init(format: "graduationDate != NULL AND graduationDate < %@ ", graduationDate);
    let oldPeople = NSPredicate.init(format: "graduationDate == NULL AND birthday > %@ ", cutOffBirthday);
    let predicate = NSCompoundPredicate.init(orPredicateWithSubpredicates: [graduates, oldPeople]);
Jon Rose
  • 8,373
  • 1
  • 30
  • 36