gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:43:51 24 4
gpt4 key购买 nike

我正在尝试更新 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

最佳答案

您在此处创建一个新对象

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

关于swift - 更新 Core Data 中的值会导致 Swift 中出现重复条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56228108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com