簡體   English   中英

解析 JSON 並將數據保存到 realm 是否可能?

[英]parse JSON and saving data to the realm is it possible?

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
}

這是我的 Model。 我可以成功解析它們並在 UITableViewCell 上顯示它們,但我無法將它們保存到 realm 因為它們是結構。 為了保存到 realm,我需要將它們轉換為 class 和 Realm object。 但是我如何將它們轉換為嵌套的 class。 我想使用相同的 model 來解析和保存數據到 realm 可以嗎?

可能有 100 種不同的解決方案。 一種選擇是使 object 成為符合可編碼協議的 Realm object。 像這樣的東西(未經測試:更多的概念解決方案)

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

or change the model in the question to a class and add a function to save a realm object with the data. 同樣,沒有經過測試,所以這只是概念性的。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM