Core data not being updated after managedContext.save but no errors thrown

时间:2019-04-17 02:26:39

标签: ios swift xcode

I'm trying to update an already saved entry in Core data, objectContext isn't nil neither is the managedObject. The new values get set to the managedObject with said Id. No errors are thrown when calling managedContext.save() but no changes are reflected in the coreData

I have tried using setValue() no avail and I have searched far and wide on google and stack overflow for a similar problem and most of the time it says to say that the managedObject is 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)")
                        }
                    }
            }

        }

1 个答案:

答案 0 :(得分:0)

实际上,我使用上述建议的谓词重写了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)
        }
    }