在Core Data中更新值会导致Swift中出现重复的条目

时间:2019-05-20 20:59:08

标签: swift core-data editing

我正在尝试从iPad应用程序的核心数据中更新值。不幸的是,每次我更新数据时,它都会创建一个重复的条目。

我在下面的代码中编码,该代码采用包含值的参数并尝试更新。但不幸的是,它创建了重复条目,而不是更新现有条目。

        let appDelegate = UIApplication.shared.delegate as! AppDelegate

        let context = appDelegate.persistentContainer.viewContext

        let entity = NSEntityDescription.entity(forEntityName: "Project", in: context)
        let newProject = NSManagedObject(entity: entity!, insertInto: context)

        let projectID = 1

        newProject.setValue(projectID, forKey: "projectID")
        newProject.setValue(projectName, forKey: "projectName")
        newProject.setValue(projectFinalDueDate, forKey: "projectFinalDueDate")
        newProject.setValue(ProjectNotes, forKey: "projectNotes")
        newProject.setValue(projectPriority, forKey: "projectPriority")
        newProject.setValue(projectAddedDate, forKey: "projectAddedDate")

        do {
            try context.save()
            showMessage(message: "Successfully update project", messageType: "success")
        } catch {
            showMessage(message: "Failed to update project", messageType: "error")
        }

很抱歉,如果我使用的关键字错误,请注意我是Core Data的新手,就像几天前一样,我开始使用它。

感谢有人能帮助我解决这个问题

Please find the screen recording of the issue

1 个答案:

答案 0 :(得分:0)

您在此处创建一个新对象

let newProject = NSManagedObject(entity: entity!, insertInto: context)

因此它将添加一个新对象,您需要使用谓词并根据一些主键更新退休值,然后保存上下文,如

    //As we know that container is set up in the AppDelegates so we need to refer that container.
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }

    //We need to create a context from this container
    let managedContext = appDelegate.persistentContainer.viewContext

    let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "Project")
    fetchRequest.predicate = NSPredicate(format: "projectID  = %d",1)
    do
    {
        let test = try managedContext.fetch(fetchRequest)

         guard let newProject = test.first else { return }
            // update here 

           try managedContext.save()

        }
    catch
    {
        print(error)
    }

}