尝试使用NSPredicate
过滤我的Realm数据库时,我总是遇到以下错误:
属性'text'不是'getType'
类型对象中的链接
我想过滤我的Realm数据库,只显示其中包含特定文本的项目。这就是我尝试过的:
let realm = try! Realm()
let predicate = NSPredicate(format: "typez.text.filter = 'special'")
let filterThis = realm.objects(Publication).filter(predicate)
print(filterThis)
我的模型类的相关部分是:
class Publication: Object, Mappable {
dynamic var id: Int = 0
var typez = List<getType>()
dynamic var url: String?
}
class getType: Object, Mappable {
dynamic var text: String = ""
}
答案 0 :(得分:10)
您提到模型类的相关部分如下所示:
class Publication: Object, Mappable {
dynamic var id: Int = 0
var typez = List<getType>()
dynamic var url: String?
}
class getType: Object, Mappable {
dynamic var text: String = ""
}
如果我理解正确,您希望查找Publication
个typez
个实例,其text
列表中的special
等于let realm = try! Realm()
let result = realm.objects(Publication).filter("ANY typez.text = 'special'")
print(result)
。你可以表达为:
manage.py migrate
答案 1 :(得分:1)
我不喜欢这里接受的答案,因为它实际上没有回答这个问题......但是它对我的帮助超过了我的意识。我会尽可能使用闭包而不是NSPredicates。这个问题的实际答案应该是@ NSGangster答案的略微修改版本:
let realm = try! Realm()
//Array of publications
let realmObjects = realm.objects(Publication)
//any publication where .text property == special will be filtered. and filter out empty array
let filterThis = realmObjects.filter({ $0.typez.filter({ $0.text == "special" } != [] ) })
print(filterThis)
..或接近那个。
但我所寻找的却有点不同。我需要一种方法来过滤多字符串的确切单词,并且使用带有“CONTAINS”的NSPredicate将匹配任何包含子字符串,例如搜索“红色”将匹配“fred”。 Realm还不支持“LIKE”或正则表达式,所以使用闭包是我唯一可以工作的东西:
//I was going for a "related terms" result for a dictionary app
let theResults = terms.filter(
{
//Looking for other terms in my collection that contained the
//title of the current term in their definition or more_info strings
$0.definition.components(separatedBy: " ").contains(term.title) ||
$0.more_info.components(separatedBy: " ").contains(term.title)
}
)
我花了很多时间搜索,希望这可以帮助其他有类似问题的人。
答案 2 :(得分:0)
我通常不直接使用NSPredicate,而是在过滤器参数中执行内联谓词闭包。
let realm = try! Realm()
//Array of publications
let realmObjects = realm.objects(Publication)
//any publication where .text property == special will be filtered. and filter out empty array
let filterThis = realmObjects.filter({ $0.getType.filter({ $0.text == "special" } != [] ) })
print(filterThis)