ios - 如何在一对多关系中更新核心数据模型
问题描述
我有一对多的核心数据模型,我正在寻找更新新车模型,即“Maruti”下的“Alto”。
let appD = UIApplication.shared.delegate as! AppDelegate
let context = appD.persistentContainer.viewContext
let person = Person(context: context)
person.firstName = "jjj"
person.lastName = "sss"
let marutiModel = Vehicals(context : context)
marutiModel.companyName = "Maruti"
let marutiVehical1 = CarModel(context : context)
marutiVehical1.carModelName = "Swift"
let marutiVehical2 = CarModel(context : context)
marutiVehical2.carModelName = "Waganor"//later on i want to add "Alto"
marutiModel.addToVehicalModel(marutiVehical1)
marutiModel.addToVehicalModel(marutiVehical2)
我试过setValue(
方法,但不知道把它放在哪里。我的要求是添加新车型。
解决方案
请对您的代码进行一些更改。NSSet
添加多辆车时需要使用参考示例代码。
func update() {
let appD = UIApplication.shared.delegate as! AppDelegate
let context = appD.persistentContainer.viewContext
let person = Person(context: context)
person.firstName = "jjj"
person.lastName = "kkkk"
let marutiModel = Vehicals(context : context)
marutiModel.companyName = "Maruti"
let marutiVehical1 = CarModel(context : context)
marutiVehical1.carModelName = "Swift"
let altoVehical = CarModel(context : context)
altoVehical.carModelName = "Alto"
// add like below
person.vehicals = NSSet(array: [marutiModel, marutiVehical1, altoVehical])
..... // your code for adding or update
}
推荐阅读
- typescript - 使用 webpack 编译打字稿时出错
- c# - 如何为每个对象创建一个数组并将其添加到列表(c#)
- python - 如何在 Python 中同时读取 ANSI 和 Unicode 编码文件
- loops - 使用 lisp 循环宏的高级循环
- sql-server - 通过 Flyway 运行批处理脚本时出现 SQL 错误 586
- python - 使用 Python 和 BOTO3 列出 AWS IP 和设备
- aws-step-functions - 为什么没有错误时阶跃函数会自行取消
- r - 为什么某些 R 代码必须包含在 Bookdown 的 index.Rmd 中?
- date - 为什么 Intl.DateTimeFormat 根据年份在 Safari 中返回不同的月份?
- java - Java:使用(透明)HTTP 代理时隐藏我的 IP