根据属性的值检索单个Realm对象

use*_*745 9 realm swift3

如何在使用Realm检索数据时返回带有值的类?我正在尝试使用此代码,但不允许使用swift 3:

static func getInfoById(id: String) -> DataInfo {
    let scope = DataInfo ()
    let realm = try! Realm()
    scope = realm.objects(DataInfo.self).filter("IdInfo == %@", id)
    return scope
}
Run Code Online (Sandbox Code Playgroud)

chr*_*nse 19

您的代码realm.objects(DataInfo.self).filter("IdInfo == %@", id)返回一个Results<DataInfo>(DataInfo的过滤集合),因此您实际上并没有返回一个DataInfo对象.您可以致电从结果中scope.first!获取一个DataInfo.

static func getInfoById(id: String) -> DataInfo {
    let realm = try! Realm()
    let scope = realm.objects(DataInfo.self).filter("IdInfo == %@", id)
    return scope.first!
}
Run Code Online (Sandbox Code Playgroud)

虽然,我不建议强行展开,因为找不到任何物品,强行展开零值会导致崩溃.因此,您可以返回DataInfo?.

static func getInfoById(id: String) -> DataInfo? {
    let realm = try! Realm()
    let scope = realm.objects(DataInfo.self).filter("IdInfo == %@", id)
    return scope.first
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您在Realm Object子类中明确声明了您IdInfo的主键,则可以realm.object(ofType: DataInfo.type, forPrimaryKey: id)改为使用.

static func getInfoById(id: String) -> DataInfo? {
    let realm = try! Realm()
    return realm.object(ofType: DataInfo.self, forPrimaryKey: id)
}
Run Code Online (Sandbox Code Playgroud)