根据属性

时间:2016-09-28 00:10:43

标签: 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
}

1 个答案:

答案 0 :(得分:17)

您的代码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!
}

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

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

或者,如果您在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)
}