具有不同表视图部分的领域过滤器字符串

时间:2018-12-15 12:42:36

标签: swift realm nspredicate

我有一个表格视图,最多可显示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 Savage”,“ 6ix9ine”,“ 2 Pac”等。

MATCHES由于某种原因无法使用,我尝试过

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

我正在寻找一种过滤器,该过滤器可以使我了解这种行为-name[0]上的IN运算符也不起作用(效率低下)。

任何帮助表示感谢,谢谢!

1 个答案:

答案 0 :(得分:1)

Sadly Realm确实不支持MATCHES的{​​{1}}运算符。针对您特定问题的一种可能的解决方法是对所有可能的单个数字使用NSPredicate运算符,并使用对所有数字的BEGINSWITH s构成复合谓词。

OR

然后,您只需要使用此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'") ,以防startsWithNumberPredicate查找其beginningLetter == "#"属性以数字开头的所有Artist

name