Valerio Ventucci
Valerio Ventucci

Reputation: 77

Can I get a string from Realm Database object in Swift 5?

I'm writing an app that uses Realm to store data locally on an iOS device.

Now I want to populate a list using the properties of that object (documentNumber, date, etc...).

The problem I'm facing is that, when the app is running, exception made for the Integers, every other property of my object is shown only by its name in the table and not by its value.

For example, if I have an object with the name property with its value set to Bob, the table is showing name instead of Bob

I've checked the DB and it contains all of the fields with the correct values

The code I'm using:

import SwiftUI

struct ItemDocumentsView2: View {
    var documents = queryDocuments()
    
    var body: some View {
            List{
                ForEach(documents, id: \.self) { document in
                    Text(document.document) // String -> shows "documentNumber" instead of the actual number
                        .listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0))

                    Text(document.date) // Integer -> shows the integer correctly
                            .listRowInsets(.init(top: 0, leading: 0, bottom: 0, trailing: 0))
                }
        }
    }
}

The Document class is this:

import Foundation
import RealmSwift  
    
    class Documents : Object, Codable{
        @objc var id : CLong
        @objc var document : String
        @objc var date : CLong

        init(id: CLong, document : String, date : CLong?){
               self.id = id
               self.document = document
               self.date = date
           }

        override init(){
               self.id = 10000000
               self.document = "document"
               self.date = 100000000
           }

}

the query method:

func queryDbForDocuments() -> [Documents]{
    let realm = try! Realm()
    
    let documents = realm.objects(Documents.self)
    return Array(documents)
}

Upvotes: 0

Views: 592

Answers (1)

David Pasztor
David Pasztor

Reputation: 54716

Your object definition is flawed, you need to add the dynamic keyword to all persisted properties.

class Documents : Object, Codable{
    @objc dynamic var id: CLong
    @objc dynamic var document: String
    @objc dynamic var date: CLong
    
    init(id: CLong, document: String, date: CLong){
        self.id = id
        self.document = document
        self.date = date
    }
    
    override init(){
        self.id = 10000000
        self.document = "document"
        self.date = 100000000
    }
    
}

Upvotes: 0

Related Questions