我可以从 Swift 5 中的领域数据库对象获取字符串吗?

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

我正在编写一个使用 Realm 在 iOS 设备上本地存储数据的应用程序。

现在我想使用该对象的属性(documentNumber、日期等...)来填充列表。

我面临的问题是,当应用程序是 运行 时,整数异常,我的对象的每个其他 属性 在 table 而不是按其值。

例如,如果我有一个 name 属性 的对象,其值设置为 Bob,则 table 显示的是 nameBob

我检查了数据库,它包含所有具有正确值的字段

我使用的代码:

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))
                }
        }
    }
}

文档class是这样的:

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
           }

}

查询方式:

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

您的对象定义有缺陷,您需要为所有持久化属性添加 dynamic 关键字。

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
    }
    
}