【问题标题】:How can I decode these models with Realm?如何使用 Realm 解码这些模型?
【发布时间】:2021-08-23 19:44:21
【问题描述】:

我想将这些模型用于领域和 Json 编码。我怎样才能做到这一点?据我了解,当我使用 Dictionary 时,Realm 不接受它。

class QuestionContainer: Codable {
    
    var questionCategories: [Question]
}

class Question: Object, Codable, Identifiable {
    
    @objc dynamic var title: String
    @objc dynamic var id: String
    @objc dynamic var questions: [QuestionList]
}

class QuestionList: Object, Codable, Identifiable {
    
    @objc dynamic var id: String
    @objc dynamic var question: String
    @objc dynamic var isQuestionImage, isSectionImage: Bool
    @objc dynamic var imageURL: String
    @objc dynamic var imageData: Data?
    @objc dynamic var sections: [QuestionSections.RawValue : String]
    @objc dynamic var selected: String
    @objc dynamic var correct: String
}

enum QuestionSections: String, Codable {
    case A = "A"
    case B = "B"
    case C = "C"
    case D = "D"
}

【问题讨论】:

  • 您能否附上您尝试过的代码?我们不是代码编写服务,我们想了解您在哪里卡住了 - 包括您的代码,我们会让我们知道您遇到困难的部分。

标签: swift realm


【解决方案1】:

您的模型应如下所示:


class QuestionContainer: Object, Codable {
    
    @Persisted var questionCategories: List<Question>
}

class Question: Object, Codable, Identifiable {
    
    @Persisted var title: String
    @Persisted var id: String
    @Persisted var questions: List<QuestionList
}

class QuestionList: Object, Codable, Identifiable {

    @Persisted var id: String
    @Persisted var question: String
    @Persisted var isQuestionImage: Bool 
    @Persisted var isSectionImage: Bool
    @Persisted var imageURL: String
    @Persisted var imageData: Data?
    @Persisted var sections: Map<String, String>
    @Persisted var selected: String
    @Persisted var correct: String
}

【讨论】:

  • 请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。
  • @Persisted var sections: Map&lt;String, String&gt;我无法使其可编码。错误:Type 'QuestionList' does not conform to protocol 'Decodable' | Type 'QuestionList' does not conform to protocol 'Encodable'
猜你喜欢
  • 2017-04-23
  • 2021-10-10
  • 2013-02-23
  • 1970-01-01
  • 2019-09-16
  • 2018-09-04
  • 1970-01-01
  • 1970-01-01
  • 2015-01-09
相关资源
最近更新 更多