GRDB与嵌套数组同步

时间:2015-12-18 00:48:23

标签: json swift sqlite grdb

我正在使用GRDB将我的JSON有效负载同步到SQLite,但是每当我在主有效负载中有其他项目数组时,我就会遇到错误。

fatal error: unexpectedly found nil while unwrapping an Optional value

我的JSON是:

{ "newsData": [
  {
    "newsID" : 6,
    "content" : "Test",
    "author" : "Test Author",
    "published" : 1,
    "title" : "Test news",
    "dateAdded" : "2015-12-18 11:33:15",
    "imagePath" : null,
    "newsCategoryData" : [

    ],
    "shortDescription" : "Test",
    "newsTagData" : [

    ],
    "lastModified" : null
  },

你可以看到我有newsCategoryData和newsTagData作为数组。同步是:

 do {
   let jsonString =
      "{ \"newsData\": " +
        "\(responseJSON["newsData"]) " +
      "}"
    try dbQueue.inTransaction { db in
      try self.synchronizeNewsWithJSON(jsonString, inDatabase: db)
      return .Commit
    }
}

问题是newsCategoryData和newsTagData,因为如果我从有效负载中删除它们,一切都会正确同步。执行同步时是否可以忽略这两个项目,因为我将在稍后阶段同步这两个项目。

由于

编辑:

func synchronizeNewsWithJSON(jsonString: String, inDatabase db: Database) throws {
    let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
    let json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as! NSDictionary

    func jsonNewsID(jsonNews: NSDictionary) -> Int64 {
        return (jsonNews["newsID"] as! NSNumber).longLongValue
    }

    let jsonNews = (json["newsData"] as! [NSDictionary]).sort {
        return jsonNewsID($0) < jsonNewsID($1)
    }

    let news = NewsModel.fetchAll(db, "SELECT * FROM news ORDER BY newsID")

    for mergeStep in sortedMerge(
        left: news,
        right: jsonNews,
        leftKey: { $0.newsID! },
        rightKey: jsonNewsID)
    {
        switch mergeStep {
        case .Left(let news):
            try news.delete(db)

        case .Right(let jsonNews):
            let row = Row(dictionary: jsonNews)!
            let news = NewsModel(row: row)
            try news.insert(db)

        case .Common(let news, let jsonNews):
            news.updateFromJSON(jsonNews)
            try news.update(db)
        }
    }
}

0 个答案:

没有答案