gpt4 book ai didi

ios - 复合键问题 Realm Swift

转载 作者:可可西里 更新时间:2023-11-01 03:19:11 25 4
gpt4 key购买 nike

在收到 Alamofire 的响应后,我尝试使用 Objectmapperjson 对象存储到 realm 对象。下面是我写的代码:

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

我能够从我的服务器映射 json 数据。但是,我的复合键有问题。这三个变量不是唯一的,但它们的组合是唯一的,所以我不得不使用 compoundKey 作为我的主键。我正在从 compoundKey 构建 primaryKey,如下所示:

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

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

func setCompoundID(yearNp: Int, mahina: String, gate: Int) {
self.yearNp = yearNp
self.mahina = mahina
self.gate = gate
compoundKey = compoundKeyValue()
}

compoundKey 的定义根据 Github issues在这儿。我有 31 部词典要存储在我的数据库中,但我只能存储最后一部词典。我确定这是一个复合键问题,因为此代码库能够将数据存储在另一个表中,该表具有唯一字段作为主键,而在此数据库表中并非如此。我是否声明了我的 compoundKey 错误?

最佳答案

我没有使用 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)
}

请改成

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
}

并运行您的项目。如果 Realm 抛出 duplicated id 错误,那一定是你的 compoundKey 在初始化后没有成功更改。那么你应该检查那部分。也许您应该手动调用它,或者覆盖您的 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)
}

关于ios - 复合键问题 Realm Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42593056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com