如何在使用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
}

最佳答案

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

虽然,我不建议强制展开,因为找不到任何项目,而强制展开nil值会导致崩溃。因此,您可以改为返回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)
}

关于realm - 根据属性值检索单个Realm对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39736125/

10-16 17:39