Reputation: 16278
I have an entity A
that has many
B
. B
belongs to
A
.
When I load data from network, since I've read performing upsert operations with core data is either imposible or that's not the way it's supposed to be handled, I went for the delete/insert way.
When I try to delete all A
, I get an Code=133020
NSMergeConflict
. It makes sense because: 1) Where would those B
entities that belongs to A
end up, and 2) I don't want to delete B
as in a delete cascade
. I literally just want to update A
.
That being said, it is clear delete/update is not the way to go (or at least not the way I'm doing it). So what's the proper way to handle this?
Upvotes: 0
Views: 84
Reputation: 80271
Right, delete update would require you to keep track of the to-many relationship objects as well and re-assign them to the new object. Because you also have to re-assign all other attributes, this seems to be much more work than just checking if the object already exists.
I am sure your network service has some unique attribute, such as an idNumber. You can use that to first do a lookup.
let filteredAObjects = allAObjects.filter { $0.idNumber == idNumberFromWebService }
let objectToUpdate = filteredAObjects.count == 0 ?
NSEntityDescription.insertNewObjectForEntityWithName("A",
inManagedObjectContext: moc) as! A :
filteredAObjects.first
Upvotes: 2