gpt4 book ai didi

arrays - 更新 NSManagedObjects 数组

转载 作者:行者123 更新时间:2023-11-28 11:36:28 24 4
gpt4 key购买 nike

我正在使用 CoreData 和 swift 并尝试更新一组 NSManagedObjects。但是,当我尝试在上下文中更新记录中的两个键。我正在使用以下代码行来执行更新:"erManagedObject.setValue([(true, forKey: "aKey"),(false, forKey: "anotherKey")])"

public func updateRecordsForEntityManagedObject(_ entity: String, erManagedObject: [NSManagedObject]){
// Create the Fetch Request
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
let recordCount = erManagedObject.count
print(" Total Records: \(recordCount)")
for i in 1...recordCount {
// I receive the error here
erManagedObject.setValue([(true, forKey: "aKey"),(DateUtilities().getTimestamp(), forKey: "timeStampKey")])
}

非常感谢任何帮助!

最佳答案

替换

 for i in 1...recordCount {
// I receive the error here
erManagedObject.setValue([(true, forKey: "aKey"),(false, forKey: "anotherKey")])
}

erManagedObject.forEach { 
$0.setValue(true, forKey: "aKey")
$0.setValue(false, forKey: "anotherKey")
}

因为你应该使用循环项来 setValue 而不是数组本身


 let request = NSFetchRequest<NSFetchRequestResult>(entityName:entity)

do {
let result = try context.fetch(request) as! [ModelName]
result.forEach {
$0.someKey = ""
}
// save context here
}
catch {
print(error)
}

关于arrays - 更新 NSManagedObjects 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55230686/

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