我正在尝试更新Core数据中已保存的条目,objectContext也不为零,managedObject也不为零。新值将设置为带有所述ID的managedObject。调用managedContext.save()时不会引发任何错误,但coreData中不会反映任何更改

我尝试使用setValue()无济于事,并且我在google和堆栈溢出中进行了广泛的搜索以寻找类似的问题,并且大多数情况下它说的是ManagedObject为nil。

    var taskName:String!
    var resultsController: NSFetchedResultsController<Tasks>!

    // MARK: - Properties
    // Manage objects and update tasks
    //var resultsController: NSFetchedResultsController<Tasks>!
    var managedContext: NSManagedObjectContext!
    var tasksArray = [NSManagedObject]()
    var fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Tasks")


func settextfields() {
        let res = resultsController.fetchedObjects!
        print(res)
        for r in res {
            if r.name == taskName {
                txt_name.text = "\(r.name ?? "Task name" )"
                txt_date.text = "\(r.date ?? "Task date")"
                segmentedBtn.selectedSegmentIndex = Int(r.priority)
            }
        }
    }

    func loadTable() {
        let request: NSFetchRequest<Tasks> = Tasks.fetchRequest()
        // Sort by date
        let sortDescriptor = NSSortDescriptor(key: "date", ascending: true)
        request.sortDescriptors = [sortDescriptor]
        resultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: coreData.managedContext, sectionNameKeyPath: nil, cacheName: nil)

        // Fetch data
        do {
            try resultsController.performFetch()
            print("Fetch successful")
        } catch  {
            print("Error performing fetch: \(error)")
        }
    }

    @IBAction func saveEdit(_ sender: Any) {
                guard let name = txt_name.text, !name.isEmpty else {
                    return
                }

                guard let date = txt_date.text, !date.isEmpty else {
                    return
                }


        do {
            loadTable()
             let res = resultsController.fetchedObjects!
                for r in res {
                    i += 1
                    if r.name == taskName {
                        print(r)
                        guard let name = txt_name.text, !name.isEmpty else {
                            return
                        }
                        guard let date = txt_date.text, !date.isEmpty else {
                            return
                        }
                        do {
                            r.name = name
                            r.date = date
                            r.priority = Int16(segmentedBtn.selectedSegmentIndex)
                        }

                        do {
                            try managedContext.save()
                            print(managedContext, r)
                            dismiss(animated: true)
                            print("Edit Successful!")
                        } catch  {
                            print("Error saving task: \(error)")
                        }
                    }
            }

        }

最佳答案

实际上,我使用上述建议的谓词重写了save函数,并且它起作用了。然后我将viewWillLoad添加到mainViewController以在条目更新后重新加载tableView

@IBAction func saveEdit(_ sender: Any) {
        guard let name = txt_name.text, !name.isEmpty else {
            return
        }

        guard let date = txt_date.text, !date.isEmpty else {
            return
        }


        do {
            let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "Tasks")
            fetchRequest.predicate = NSPredicate(format: "name = %@", taskName)
            let test = try managedContext.fetch(fetchRequest)
            let obj = test[0] as! NSManagedObject

            obj.setValue(name, forKey: "name")
            obj.setValue(date, forKey: "date")
            obj.setValue(Int16(segmentedBtn.selectedSegmentIndex), forKey: "priority")


            do {
                try managedContext.save()
                dismiss(animated: true)
                print("Edit Successful!")
            } catch  {
                print("Error saving task: \(error)")
            }
        } catch {
            print(error)
        }
    }

09-07 11:47