0

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?

Thomas Tempelmann
  • 11,045
  • 8
  • 74
  • 149
anders32
  • 295
  • 1
  • 4
  • 11
  • 1
    What errors are you getting? Have your tried `"( name contains[cd] %@ )AND (position in %@)",name,[position1,position2])` ? – Paulw11 May 15 '16 at 02:32
  • thanks, that was a better way than I was doing it! – anders32 May 15 '16 at 03:02
  • Turns out I mistakenly thought the above wasn't working. Before I was trying to add strings using traditional Swift interpolation via a for loop to an NSPredicate - which I suspect caused the Core Data errors. Then I forgot that was the problem after trying things with NSCompoundPredicate. – anders32 May 15 '16 at 03:04

1 Answers1

1

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]
Saeed Jahed
  • 821
  • 5
  • 8