首页 > 解决方案 > 如何在一对多关系中更新核心数据模型

问题描述

我有一对多的核心数据模型,我正在寻找更新新车模型,即“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(方法,但不知道把它放在哪里。我的要求是添加新车型。

标签: iosswiftcore-datacore-data-migration

解决方案


请对您的代码进行一些更改。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

}

推荐阅读