如何以一对多关系更新核心数据模型

问题描述 投票:0回答:1

我有一对多的核心数据模型,我正在寻找更新的新车模型,即“ Maruti”下的“ Alto”​​。

enter image description here

    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(方法,但不知道确切地放在哪里。我的要求是添加新的汽车模型。

ios swift core-data core-data-migration
1个回答
0
投票

请对您的代码进行一些更改。添加多个车辆时需要使用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"

    person.vehicals =  NSSet(array: [marutiModel, marutiVehical1, altoVehical]) // Important 

   ..... // your code for adding or update

}
© www.soinside.com 2019 - 2024. All rights reserved.