【发布时间】:2017-07-24 09:36:33
【问题描述】:
在收到来自Alamofire 的响应后,我正在尝试使用Objectmapper 将json 对象存储到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 错误?
【问题讨论】:
标签: ios json swift3 realm objectmapper