I developed an app focused on health and fitness and to save workout data I use Core Data. In a small number of users (<0.1%), I get the following error:
Fatal Exception: NSInvalidArgumentException, Illegal attempt to establish an 'X' relationship between objects in different contexts.
This error occurs when I try to save the training program. If I log-on with the same user account on my device, this error does not happen.
This is my save function:
func saveTraningProgramDB(trainingPro:RetornoTreino) {
let db = getContext()
for ficha in (trainingProgram.programa?.fichas)! {
let fichasDB = FichasNovoDB(context: db)
fichasDB.nome = ficha.nome
....
for atividade in ficha.atividades! {
for atividadePrograma in (programaTreino.programa?.atividades)! {
if atividade.codigoAtividade == String(atividadePrograma.codigoAtividade ?? 0) {
let atividadesDB = AtividadesNovoDB(context: bancoDeDados)
...
for serie in atividade.series! {
let seriesDB = SeriesNovoDB(context: bancoDeDados)
...
atividadesDB.addToSeries(seriesDB)
}
for ajuste in atividade.ajustes! {
...
atividadesDB.addToAjustes(ajustesDB)
}
fichasDB.addToAtividades(atividadesDB)
}
}
}
db(fichasDB)
}
do {
try db.save()
} catch {
db(error)
}
}
Does anyone have any idea what might be going on, or how can I do to simulate the problem as it only happens on the client device ?
Thanks for all replies!
NOTE: Sorry for my English, it is not my native language.