我正在使用CoreData和swift并尝试更新NSManagedObjects数组。但是,当我尝试在上下文中更新记录中的两个键时,我收到“类型值'[NSManagedObject]'没有成员'setValue'”。我正在使用以下代码行来执行更新:“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)
}
erManagedObject是NSManagedObjects的数组。 (更新) - 您正在错误地使用setValue方法,它不应该接受数组。看文件
https://developer.apple.com/documentation/coredata/nsmanagedobject/1506397-setvalue
我想你想做
erManagedObject[i].setValue...
注意:你的for循环将崩溃,因为你的数组将超出界限..你的for循环应该从0迭代.. <erManagedObjects.count
for i in 0 ..< recordCount {
erManagedObject[i].setValue...
}
另外...
for managedObject in erManagedObject {
managedObject.setValue...
}