【问题标题】:Can I get a string from Realm Database object in Swift 5?我可以从 Swift 5 中的领域数据库对象中获取字符串吗?
【发布时间】:2021-01-04 23:18:50
【问题描述】:

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

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

我面临的问题是,当应用程序运行时,整数出现异常,我的对象的所有其他属性仅在表中显示为它的名称,而不是它的值。

例如,如果我有一个具有name 属性的对象,其值设置为Bob,则表格将显示name 而不是Bob

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

我正在使用的代码:

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

Document 类是这样的:

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

【问题讨论】:

  • 您需要edit 您的问题以minimal reproducible example 的形式包含所有相关代码,以便使问题成为主题。 documents 的类型是什么?您需要包含queryDocuments 的定义以及您的领域模型。
  • 你说得对,我已经编辑了问题并添加了代码

标签: swift realm


【解决方案1】:

您的对象定义有缺陷,您需要将 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
    }
    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 2011-09-10
    • 2013-11-10
    • 1970-01-01
    • 2017-12-11
    • 2016-03-28
    • 1970-01-01
    相关资源
    最近更新 更多