复合键问题Realm Swift

ama*_*ain 8 json realm ios objectmapper swift3

我收到响应后试图将json对象存储到realm对象.以下是我写的代码:ObjectmapperAlamofire

  func getTodayData() {

    Alamofire.request("https://myapipoint.json").responseJSON{ (response) in

        guard response.result.isSuccess, let value = response.result.value else {
            return
        }
        let json = JSON(value)


        guard let realm = try? Realm() else {
            return
        }

        realm.beginWrite()

        for (_, value): (String, JSON) in json {

            let tpTodayOb = Mapper<TPToday>().map(JSONObject: value.dictionaryObject)

            realm.add(tpTodayOb!, update: true)
        }

        do {
            try realm.commitWrite()
        }
        catch {
            print("Error")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我能够json从我的服务器映射数据.但是,我的复合键存在问题.这三个变量不是唯一的,但它们的组合是唯一的,所以我不得不compoundKey用作我的主键.我建立primaryKeycompoundKey如下:

public dynamic var compoundKey: String = "0-"

public override static func primaryKey() -> String? {
   // compoundKey = self.compoundKeyValue()
    return "compoundKey"
}

private func compoundKeyValue() -> String {

    return "\(yearNp)-\(mahina)-\(gate)"
}
Run Code Online (Sandbox Code Playgroud)

这是我初始化我的三个变量的地方.

func setCompoundID(yearNp: Int, mahina: String, gate: Int) {
    self.yearNp = yearNp
    self.mahina = mahina
    self.gate = gate
    compoundKey = compoundKeyValue()
}
Run Code Online (Sandbox Code Playgroud)

compoundKey根据Github问题的定义就在这里.我有31个字典存储在我的数据库中,但我只能存储最后一个字典.我确信这是一个复合键问题,因为此代码库能够将数据存储在另一个具有唯一字段作为主键的表中,而在此数据库表中并非如此.我compoundKey说错了吗?

Owe*_*hao 1

我没有使用Alamofire,所以我认为你的代码Alamofire部分是正确的。您没有给出 JSON 的结构,根据上下文,我假设您的 JSON 包含 31 个字典。另外,我一开始就假设 Realm 数据库是空的。如果没有,请将其留空。

我相信问题就在这里。

for (_, value): (String, JSON) in json {
    let tpTodayOb = Mapper<TPToday>().map(JSONObject: value.dictionaryObject)

    realm.add(tpTodayOb!, update: true)
}
Run Code Online (Sandbox Code Playgroud)

请更改为

for (_, value): (String, JSON) in json {
    let tpTodayOb = Mapper<TPToday>().map(JSONObject: value.dictionaryObject)

    realm.add(tpTodayOb!, update: false) // you don't need `update:true`, unless you want to rewrite it intendedly
}
Run Code Online (Sandbox Code Playgroud)

并运行您的项目。如果Realm抛出重复的id错误,那一定是你的compoundKeys初始化后没有成功更改。那么你应该检查那部分。也许您应该手动调用它,或者覆盖函数的相应部分init

for (_, value): (String, JSON) in json {
    let tpTodayOb = Mapper<TPToday>().map(JSONObject: value.dictionaryObject)
    tpTodayOb.setCompoundID(yearNp: Int, mahina: String, gate: Int)
    realm.add(tpTodayOb!, update: false)
}
Run Code Online (Sandbox Code Playgroud)