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 manyCityEntity
as I haveWeatherEntity
, which is wrong as I am expecting only oneCityEntity
.When saving
WeatherEntity
, the relationship with theCityEntity
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.
This is the way I set the relationship in the CoreDataModel
:
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.