使用Swift过滤Realm对象 [英] Filtering Realm objects with Swift
本文介绍了使用Swift过滤Realm对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试使用NSPredicate
过滤Realm数据库时,总是出现以下错误:
I always get the following error when trying to filter my Realm database using NSPredicate
:
属性文本"不是类型为"getType"的对象中的链接
Property 'text' is not a link in object of type 'getType'
我想过滤我的Realm数据库以仅显示其中包含某些特定文本的项目.这是我尝试过的:
I want to filter my Realm database to show only the items that have some specific text in them. This is what I've tried:
let realm = try! Realm()
let predicate = NSPredicate(format: "typez.text.filter = 'special'")
let filterThis = realm.objects(Publication).filter(predicate)
print(filterThis)
我的模型类的相关部分是:
The relevant portion of my model classes is:
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 = ""
}
推荐答案
我通常不直接使用NSPredicate's,而是在过滤器参数内执行内联谓词关闭.
I don't usually use NSPredicate's directly, instead I do an inline predicate closure within the filter paramter.
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)
这篇关于使用Swift过滤Realm对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文