我不知道如何根据用户选择组合谓词。以下是我的数据概述。
Person.swift
class Person: Object {
let id = RealmOptional<Int>()
dynamic var name = ""
dynamic var console = ""
override static func primaryKey() -> String {
return "id"
}
示例json数据
{
"id": 822,
"name": "Ron",
"console": "XBox"
},
{
"id": 823,
"name": "Jenny"
"console": "Playstation 4"
}
例如,我有很多数据和控制台包括“XBox”,“Playstation 4”,“Wii”,“Sega”或“PS Vita”。我创建了一个复选框过滤选项,允许用户选择他们想要过滤的选项,并显示拥有哪个控制台的人的姓名。
例如,如果他们同时选择“XBox”和“Playstation 4”,我如何预测它们并显示人名的结果?目前我只能展示一个这样的选项。
var player: Results<Person>!
func filter(sender: AnyObject) {
let realm = try! Realm()
self.player = realm.objects(Person).filter("%K = %@", "console", "XBox")
}
答案 0 :(得分:15)
您不应该动态制作NSPredicate查询字符串。以编程方式创建NSCompoundPredicate
要容易得多(也更安全)。您可以将NSPredicate
传递给Realm的RealmCollectionType.filter(...)
方法。以下是获取拥有Xbox或Playstation 4的所有Person
的示例:
// 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)
答案 1 :(得分:0)
快捷键5
多个谓词
组合谓词与NSCompoundPredicate:
let predict = NSPredicate.init(format: "console == %@", "Xbox")
let predict2 = NSPredicate.init(format: "console == %@", "Playstation 4")
let query = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.or, subpredicates: [predict,predict2])
let player = realm.objects(Person).filter(query)