您不应动态制作NSPredicate查询字符串.以NSCompoundPredicate
编程方式创建更容易(也更安全).您可以将NSPredicate
s 传递给Realm的RealmCollectionType.filter(...)
方法.这是一个让所有Person
拥有Xbox或Playstation 4的人的例子:
// could use .AndPredicateType here too, depending on what you want let query = NSCompoundPredicate(type: .OrPredicateType, subpredicates: [NSPredicate(format: "console = 'Xbox'"), NSPredicate(format: "console = 'Playstation 4')]) let player = realm.objects(Person).filter(query)
虽然在您的情况下,IN
如果您需要OR
语义,最好使用查询:
let selectedConsoles = ["Xbox", "Playstation 4"] let player = realm.objects(Person).filter("console IN %@", selectedConsoles)