How to add unique constraints for some fields in Core Data

There’s a new section in the sidebar when selecting an entity in the editor for Core Data. You can set what constraint(s) you want to be unique across all instances of an entity

For automatic conflict resolution during saves, you’ll need to make sure you’ve got a merge policy set for your managed object context or else you’ll just get errors when saving (which might actually be what you want)

[managedObjectContext setMergePolicy:NSMergeByPropertyObjectTrumpMergePolicy];

The “Swift version” is exactly the same

managedObjectContext.mergePolicy = .mergeByPropertyObjectTrumpMergePolicyType

Keep in mind conflict resolution only happens during saves, and not inserts. So if you’re making use of a NSFetchedResultsController you will see entities with non-unique constraints as they’re inserted.

enter image description here

If you want to sure you have no entities with non-unique constraints in your managed object context without saving (if you’re making use of a FRC), this answer is still probably the best way to go. Although, keep in mind, it’s expensive if you’re doing a lot of inserts, since NSFetchRequests are expensive operations.

Sample code for this demo can be found here

Leave a Comment