【问题标题】:Update an Array of NSManagedObjects更新 NSManagedObjects 数组
【发布时间】:2019-08-09 08:55:06
【问题描述】:

我正在使用 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")])
     }

非常感谢任何帮助!

【问题讨论】:

    标签: arrays swift core-data nsmanagedobject


    【解决方案1】:

    替换

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

    【讨论】:

    • 嗨@Sh_Khan,非常感谢您的建议。但是,当我尝试使用它时,我收到“无法使用类型为'([(Bool,forKey:String)])'的参数列表调用'setValue'”。当我用实际参数完成它时,同样的错误,
    • 您可以尝试编辑,但最好将您的对象转换为模型而不是使用setValue
    • 非常感谢,Sh_Khan,在对您的建议进行了以下修改后,我能够使其正常工作。 erManagedObject.forEach { $0.setValue(true, forKey: "aKey") $0.setValue(false, forKey: "anotherKey") do { try managedObjectContext.save() } catch let error as NSError { print("(UPDATE_ERROR) (错误), (error.userInfo)") }
    【解决方案2】:

    erManagedObject 是一个 NSManagedObjects 数组。 (更新)-您错误地使用了 setValue 方法,它不应该包含一个数组。查看文档

    https://developer.apple.com/documentation/coredata/nsmanagedobject/1506397-setvalue

    我想你想做

    erManagedObject[i].setValue...
    

    注意:你的 for 循环会崩溃,因为你的数组会越界。你的 for 循环应该从 0 开始迭代 ..

     for i in 0 ..< recordCount {
        erManagedObject[i].setValue...
     }
    

    或者...

    for managedObject in erManagedObject {
      managedObject.setValue...
    }
    

    【讨论】:

    • 嗨,@Mocha 我尝试了您的第一个建议,但收到以下错误:“无法使用 '([Any])' 类型的参数列表调用 'setValue'”。请注意我确实更新了第二个参数。但是,即使使用初始参数,也会收到错误。
    • 您的 setValue 错误。你不应该传入一个数组。见文档developer.apple.com/documentation/coredata/nsmanagedobject/…
    • 谢谢,@Mocha,鉴于此,如果我们不使用数组,对于相应迭代的整个记录​​有什么建议吗?
    • 我不明白你的问题——你可以对多个键多次使用 setValue 方法。
    • 感谢您的帮助,摩卡。我赞成你的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    相关资源
    最近更新 更多