Home > Enterprise >  Why would my data relationship is not created in CoreData?
Why would my data relationship is not created in CoreData?

Time:09-26

I have two entities in my CoreDataModel that should be linked together with a too-many relationship on one wary and to-one on the other way.

These are the CityEntity and the WeatherEntity. The CityEntity can have multiple WeatherEntity, but not the opposite.

I have two main errors that I would like to solve.

  • When saving the data, the NSManagedObjectContext save as many CityEntity as I have WeatherEntity, which is wrong as I am expecting only one CityEntity.

  • When saving WeatherEntity, the relationship with the CityEntity is not created.

This is the code I am using to save the data.

func saveForecast() {

  let cityModel = CityModel(
    name: "Paris",
    weather: [WeatherModel(temp: 12.65), WeatherModel(temp: 12.43)]
  )

  let cityEntity = CityEntity(context: persistentContainer.viewContext)
  cityEntity.name = await cityModel.name

  for weather in await cityModel.weathers {

    let weatherEntity = WeatherEntity(context: persistentContainer.viewContext)
    weatherEntity.temp = weather.temp
    weatherEntity.city = cityEntity
  }

  do { try persistentContainer.viewContext.save() }
  catch { print(error.localizedDescription) }
}

These are the result that I get saved in my CoreDataModel, which is wrong as I have 3 CityEntity instead of one, and no relationships between my WeatherEntity and the expected CityEntity.

You can see that there is not CityEntity saved in place of the name when looking at the `WeatherEntity.

CityEntity result WeatherEntity result

This is the way I set the relationship in the CoreDataModel:

CityEntity setup WeatherEntity setup

CodePudding user response:

It seems that you (accidentally?) set the parent entity of WeatherEntity to CityEntity. That makes WeatherEntity a “sub-entity” of CityEntity, and the corresponding WeatherEntity class a subclass of CityEntity.

Then every instance of WeatherEntity is also an instance of CityEntity, and that explains why there are three instances of CityEntity in total after running your code.

Resetting the parent entity to “No Parent Entity” in the Core Data model inspector, re-generating the managed object subclasses, and cleaning all application data should solve the problem.

  • Related