Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving a single Realm object based on the value of a property

Tags:

swift3

realm

How to return a class with values while retrieving data with Realm? I am trying to use this code, but swift 3 not allowed:

static func getInfoById(id: String) -> DataInfo {
    let scope = DataInfo ()
    let realm = try! Realm()
    scope = realm.objects(DataInfo.self).filter("IdInfo == %@", id)
    return scope
}
like image 567
user1801745 Avatar asked Sep 28 '16 00:09

user1801745


1 Answers

Your code realm.objects(DataInfo.self).filter("IdInfo == %@", id) returns a Results<DataInfo> (a filtered collection of DataInfo), thus you're not really returning a DataInfo object. You can call scope.first! to get one DataInfo from the results.

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

Although, I don't recommend force-unwrapping since there can be no items found, and force-unwrapping a nil value results in a crash. Thus you can return a DataInfo? instead.

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

Alternatively, if you have explicitly stated in your Realm Object subclass that IdInfo is your primary key, you can use realm.object(ofType: DataInfo.type, forPrimaryKey: id) instead.

static func getInfoById(id: String) -> DataInfo? {
    let realm = try! Realm()
    return realm.object(ofType: DataInfo.self, forPrimaryKey: id)
}
like image 157
chrisamanse Avatar answered Oct 27 '22 23:10

chrisamanse