我有一个核心数据条目,其中存储在从API获取的数据库中的某些键和值。现在我想用更新的值更新一些核心数据条目因此我使用下面的代码:
func updateAllRecords(responseArray: [Dictionary<String, String>]) {
for settingsObject in responseArray {
if #available(iOS 10.0, *) {
let keys = settingsObject.flatMap() { $0.0 as? String }
let values = settingsObject.flatMap(){ $0.1 as? String}
let request = NSFetchRequest<ApplicationSettings>(entityName: "ApplicationSettings")
do {
let context = persistentContainer.viewContext
let searchResults = try context.fetch(request)
for settingsKeys in searchResults {
if keys.contains(settingsKeys.key!) {
settingsKeys.value = values[1]
try context.save()
}
}
} catch {
print ("There was an error")
}
} else {
}
}
}
}
我从viewcontroller调用此函数,如下所示:
var dicArray = [Dictionary<String, String>]()
let dic1 = ["IS_CIVIL_ID_MANDATORY": "Smith", "TIME_IN_MIN_BEFORE_ENABLING_START_TRIP": "Robert"]
dicArray.append(dic1)
CoreDataHandler.sharedInstance.updateAllRecords(responseArray: dicArray)
但是表中的条目没有正确更新密钥。它为两个键存储相同的值。见下文:
我在这段代码中错了?为什么为密钥存储相同的值?
答案 0 :(得分:1)
const myLib = {
get:function(){},
get2:function(){}
...
};
myLib.get();
myLib.get2();
这里1是静态的
我认为你不需要将值数组分开 只需用我的代码替换此代码
settingsKeys.value = values[1]
演示示例
for settingsKeys in searchResults {
if keys.contains(settingsKeys.key!)
{
settingsKeys.updateValue(settingObject[settingsKeys.key!], forKey:settingsKeys.key!)
try context.save()
}
}
}
<强>输出强>
[“TIME_IN_MIN_BEFORE_ENABLING_START_TRIP”:“Robert”,“IS_CIVIL_ID_MANDATORY”:“Smith”]