Nan
Nan

Reputation: 524

How to retrieve data from Realm's Results instance?

I just start to learn Realm data persistence, I start it from a iOS test project. The realm object is declared like this:

class AchievementRecord: Object {

    dynamic var dateID:String = "1111-00-00"
    dynamic var date:String = "0000-00-00"
    dynamic var apple:Int = Int(0)

    override static func primaryKey() -> String? {
        return "dateID"
    }
} 

I initialise the object in View Controller's viewDidLoad() method as this:

class AchievementRecord: Object {

dynamic var dateID:String = "1111-00-00"
dynamic var date:String = "0000-00-00"
dynamic var apple:Int = Int(0)

override static func primaryKey() -> String? {
    return "dateID"
}
}

then I declare another function to obtain the save data as:

let appleOn_05 = defaultRealm.objects(AchievementRecord.self).filter("dateID = '05-06-2017'")
print(appleOn_05)

In the console, Xcode says:

enter image description here

Because I need to retrieve the apple's number, which is 22 in the console. How can I retrieve the apple's number to demo it on the screen, how can I do it? Thanks in advance.

Upvotes: 0

Views: 1273

Answers (1)

David Pasztor
David Pasztor

Reputation: 54706

Results works like native Swift collections in many ways. If you are fetching a single object, you can just access it with Results.first let appleOn_05 = defaultRealm.objects(AchievementRecord.self).filter("dateID = '05-06-2017'").first

Subclasses of Object work like any other native class instance in Swift, so you can access their properties using the dot syntax. let apple = appleOn_05.apple

Combining the two:

if let appleOn_05 = defaultRealm.objects(AchievementRecord.self).filter("dateID = '05-06-2017'").first {
    let apple = appleOn_05.apple
}

Upvotes: 2

Related Questions