My Swift app downloads 3 databases from an online API in JSON form, and then converts the JSON objects into CoreData objects, so the app can function outside of internet access.
I have an entity Client that has a toMany relationship with entities of type Address. Address has a to-one relationship with entity Client.
Client <-->> Address
The Client to Addresses relationship has a cascade delete rule, and the Address to Client relationship has a nullify delete rule.
Client has a uniqueness constraint on the id attribute, and the context always uses NSMergePolicyType.overwriteMergePolicyType.
When a new Client NSManagedObject is instantiated, the context is saved, and a Client with the same ID is found, the new Client overwrites the old one, with one big caveat - for some unknown reason the old Address objects persist, now linked to the new Client. This results in a new copy of each Address every time the cache/database is reloaded.
I have multiple entities that have relationships and uniqueness like this that are running into the same result - duplicates of to-many object instances.
For an object like Address, there is no one attribute that can encapsulate uniqueness among all other Address objects across the container. It must be a sum of all the attributes(address1, address2, city, state, zip, etc) that is checked for uniqueness against the sum of all attributes of another Address. So I'm unsure of how to accomplish this through uniqueness constraints - as far as I can tell, uniqueness constraints cannot be expanded with if logic.
The other solution would be to change the merge behavior of the policy, or create a custom merge policy, to ensure that it actually deletes the old object(cascading down to the to-many relationship objects) before replacing it with the new object.
I'm not familiar enough with CoreData or objective-c to follow anything I've been able to find on the subject so far.
Does anyone have suggestions on how to either A. expand uniqueness constraints capabilities, B. define merge policy behavior, or C. otherwise prevent the aforementioned address objects from duplicating?
edit:
I'm suspicious that my presumptions about uniqueness constraints are wrong - see my separate question about it here