在 NSPredicates 上结合 "And" 和 "Or"
Combining "And" and "Or" on NSPredicates
我想做这样的事情:
NSPredicate(format: "name contains[cd] %@ AND (position == %@ OR position == %@), name, position1, position2)
但是,我已经尝试过了,但我不断收到严重的 Core Data 应用程序错误。然后我尝试使用 NSCompoundPredicate,但我也不能在那里组合 "AND" 和 "OR"s。
我读过 Combining 'AND' and 'OR' Condition in NSPredicate 不同之处在于提问者想要一个子集合的 "OR" 所以答案涉及一个我不想要的子查询。
我该怎么做?
我没有足够的声誉 post 发表评论。您 posted 应该可以工作。这可能有助于 post 您的更多代码以确定确切的问题。
希望它能帮助您解决问题,我将 post 结合 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]
我想做这样的事情:
NSPredicate(format: "name contains[cd] %@ AND (position == %@ OR position == %@), name, position1, position2)
但是,我已经尝试过了,但我不断收到严重的 Core Data 应用程序错误。然后我尝试使用 NSCompoundPredicate,但我也不能在那里组合 "AND" 和 "OR"s。
我读过 Combining 'AND' and 'OR' Condition in NSPredicate 不同之处在于提问者想要一个子集合的 "OR" 所以答案涉及一个我不想要的子查询。
我该怎么做?
我没有足够的声誉 post 发表评论。您 posted 应该可以工作。这可能有助于 post 您的更多代码以确定确切的问题。
希望它能帮助您解决问题,我将 post 结合 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]