【问题标题】:parse JSON and saving data to the realm is it possible?解析 JSON 并将数据保存到领域是否可能?
【发布时间】:2020-12-08 04:25:15
【问题描述】:
struct NewsModel: Codable{

    let id: Int?
    let title, newsModelDescription: String?
    let sourceID, version: String?
    let publishedAt: Int
    let readablePublishedAt: String?
    let updatedAt: Int
    let readableUpdatedAt: String
    let images: Images
    let embedTypes: String?
    let typeAttributes: TypeAttributes
    let type: String?
    let source: String?


    enum CodingKeys: String, CodingKey {
        case id, title
        case newsModelDescription
        case sourceID
        case version, publishedAt, readablePublishedAt, updatedAt, readableUpdatedAt, embedTypes, images,typeAttributes, type, source
    }
}

// MARK: - Images
struct Images: Codable {
    let square140: String

    enum CodingKeys: String, CodingKey {
        case square140 = "square_140"
    }
}

struct TypeAttributes: Codable {
    let imageLarge: String
}

这是我的模特。我可以成功解析它们并在 UITableViewCell 上显示它们,但我无法将它们保存到领域,因为它们是结构。为了保存到领域,我需要将它们转换为类和领域对象。但是我如何将它们转换为嵌套类。我想用同一个模型来解析和保存数据到领域可以吗?

【问题讨论】:

  • 为什么不让 NewsModel 成为 Realm 对象呢?或者。使它成为一个快速类并添加一个函数func saveToRealm,当调用它时会创建一个领域对象并将属性映射到托管领域属性并保存?或者。只需将其设为可编码的领域对象即可。或者。添加扩展并使其可编码。有很多选择,你试过什么?
  • @Jay 感谢您的建议。你能给我举个例子吗?

标签: json swift realm


【解决方案1】:

可能有 100 种不同的解决方案。一种选择是只使对象成为符合可编码协议的领域对象。像这样的东西(未经测试:更多的是概念解决方案)

class NewsModel: Object, Codable {
    @objc dynamic var _id = UUID().uuidString
    @objc dynamic var title = ""
    @objc dynamic var news = ""

    private enum CodingKeys: String, CodingKey {
        case _id
        case title
        case news
    }

    override class func primaryKey() -> String? {
        return "_id"
    }

    public required convenience init(from decoder: Decoder) throws {
        self.init()
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self._id = try container.decode(String.self, forKey: ._id)
        self.name = try container.decode(String.self, forKey: .title)
        self.logo = try container.decode(String.self, forKey: .news)
    }

或者将问题中的模型更改为一个类,并添加一个函数来保存一个领域对象和数据。同样,没有经过测试,所以这只是概念性的。

class RealmNewsModel: Object {
   @objc dynamic var _id = ""
   @objc dynamic var title = ""
   @objc dynamic var news = ""
}

class NewsModel, Codable {
   let _id: String?
   let title: String?
   let news: String?

   func saveToRealm {
      let news = RealmNewsModel()
      news._id = self._id
      news.title = self.title
      news.news = self.news
      try! realm.write {
          realm.add(news)
      }

【讨论】:

    猜你喜欢
    • 2021-09-24
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    • 2017-06-16
    相关资源
    最近更新 更多