Search code examples
ioscore-datanspredicatenscompoundpredicate

Combining "And" and "Or" on NSPredicates


I want to do something like this:

NSPredicate(format: "name contains[cd] %@ AND (position == %@ OR position == %@), name, position1, position2)

However, I've tried that and I keep getting serious Core Data application errors. I then tried using NSCompoundPredicate, but I can't combine "AND" and "OR"s there either.

I've read Combining 'AND' and 'OR' Condition in NSPredicate and it's different in that the questioner wanted an "OR" on a subcollection so the answer involves a subquery which I don't want.

How do I do this?


Solution

  • I don't have enough reputation to post a comment. What you have posted should work. It might help to post more of your code to identify the exact issue.

    In hopes that it helps you catch your issue, I'll post a working sample with combined AND and OR:

    let alice = Person(firstName: "Alice", lastName: "Smith", age: 24, position: "Up")
    let bob = Person(firstName: "Bob", lastName: "Jones", age: 27, position: "Left")
    let charlie = Person(firstName: "Charlie", lastName: "Smith", age: 33, position: "Right")
    let quentin = Person(firstName: "Quentin", lastName: "Alberts", age: 31, position: "Down")
    let people = [alice, bob, charlie, quentin]
    
    let predicate = NSPredicate(format: "firstName contains[cd] %@ AND (position == %@ OR position == %@)", "e", "Up", "Down")
    let filtered = (people as NSArray).filteredArrayUsingPredicate(predicate)
    
    print(filtered)
    
    // prints [Alice Smith, Quentin Alberts]