我有一个具有一些表单字段的应用程序。提交表单后,它将数据写入我的核心数据对象。但是,当再次提交表单时,它会覆盖现有数据而不是附加到它,这正是我想要发生的情况。
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let userEntity = NSEntityDescription.entity(forEntityName: "User", in: managedContext)
let newUser = NSManagedObject(entity: userEntity! , insertInto: managedContext)
newUser.setValue(titleField, forKey: "title")
newUser.setValue(firstNameField, forKey: "firstName")
newUser.setValue(lastNameField, forKey: "lastName")
newUser.setValue(emailField, forKey: "email")
newUser.setValue(affiliatedOrgField, forKey: "affiliatedOrg")
newUser.setValue(ukRegionField, forKey: "ukRegion")
newUser.setValue(privacyChecked, forKey: "privacyPolicy")
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
我尝试过使用
let userEntity = NSEntityDescription.insertNewObject(forEntityName: "User", into: managedContext)
let newUser = NSManagedObject(entity: userEntity, insertInto: managedContext)
但我的“newUser”常量出现以下错误
无法将类型“NSManagedObject”的值转换为预期参数类型“NSEntityDescription”
有人可以帮忙吗?
既然你正在使用NSPersistentContainer
您至少使用 macOS 10.12 或 iOS 10.10。 Apple 为 Core Data 添加了一些非常好的简化,因此没有必要使用基于字符串的键,但这种键的缺点是无法抵抗编译器检查。
“新核心数据模式”如下所示:
let managedContext = appDelegate.persistentContainer.viewContext
let newUser = User(context: managedContext)
newUser.title = ...
newUser.firstName = ...
事情可能就是这么简单。请让我知道这对你有没有用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)