我有一個字串串列
filterList = ['x0', 'x1', 'x2']
我的物件如下:
class Item: Object {
@Persisted var name: String?
}
x0我想獲取名稱以串列元素之一(或x1或x2)開頭的所有物件
因此,具有名稱x072or的物件x1e2將包含在結果中,但具有名稱的物件x933ory011不會
謝謝
uj5u.com熱心網友回復:
有很多方法可以做到這一點。一種選擇(在這個用例中并不實際)是使用Realm Swift Query UI
let results2 = realm.objects(Item.self).where {
$0.name.starts(with: "x0") ||
$0.name.starts(with: "x1") ||
$0.name.starts(with: "x2")
}
正如你所看到的,對于一些專案來說是可以的。如果有幾十個怎么辦?不是很實用。這就是 NSCompoundPredicate 真正閃耀的地方。看一下這個
var predicateArray = [NSPredicate]()
for name in ['x0', 'x1', 'x2'] {
let predicate = NSPredicate(format: "name BEGINSWITH[cd] %@", name)
predicateArray.append(predicate)
}
let compoundPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: predicateArray)
let results = realm.objects(Item.self).filter(compoundPredicate)
更實用的方式是串列中的元素可以根據需要而定。
還有一些其他選項,但在此用例中建議使用 NSPredicate 路由。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/468807.html
