具有不同表视图部分的Realm筛选器字符串



我有一个表视图,最多有27个部分(a-Z+#(

部分A包含名称以"A"等开头的所有对象。本例中的对象类型为Artist,具有name属性。

private var sectionIndices: [String] = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","#"]
for beginningLetter in self.sectionIndices {
print("Finding artists for (beginningLetter)")
let artists: Results<Artist>
if beginningLetter == "#" {
artists = self.artists.filter("NOT (name[0] IN %@)", self.sectionIndices)
} else {
artists = self.artists.filter("name BEGINSWITH[cd] %@", beginningLetter).sorted(byKeyPath: "name", ascending: true)
}
}

因此,除了#部分外,过滤对所有内容都很有效。基本上,每一个名字以非字母开头的艺术家都应该在那里。"21野蛮人"、"6ix9ine"、"2 Pac"等

由于某些原因匹配不起作用,我尝试了

name MATCHES %@,但领域并不真正支持它。

我正在寻找一个过滤器,让我知道name[0]上的behavior-IN运算符也不起作用(而且效率低下(。

感谢任何帮助,谢谢!

遗憾的是,Realm确实不支持NSPredicateMATCHES运算符。针对您的特定问题,一种可能的解决方法是将BEGINSWITH运算符与所有可能的个位数一起使用,并使用ORs与所有数字一起生成复合谓词。

let startsWithNumberPredicate = NSPredicate(format: "name BEGINSWITH '0' OR name BEGINSWITH '1' OR name BEGINSWITH '2' OR name BEGINSWITH '3' OR name BEGINSWITH '4' OR name BEGINSWITH '5' OR name BEGINSWITH '6' OR name BEGINSWITH '7' OR name BEGINSWITH '8' OR name BEGINSWITH '9'")

然后,只需在beginningLetter == "#"的情况下使用此startsWithNumberPredicate,即可查找其name属性以数字开头的所有Artist

private var sectionIndices: [String] = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","#"]
for beginningLetter in self.sectionIndices {
print("Finding artists for (beginningLetter)")
let artists: Results<Artist>
if beginningLetter == "#" {
artists = self.artists.filter(startsWithNumberPredicate, self.sectionIndices)
} else {
artists = self.artists.filter("name BEGINSWITH[cd] %@", beginningLetter).sorted(byKeyPath: "name", ascending: true)
}
}