Is it possible to make a Core Data attribute unique, i.e. no two MyEntity objects can have the same myAttribute?
I know how to enforce this programatically, but I'm hoping there's a way to do it using the graphical Data Model editor in xcode.
I'm using the iPhone 3.1.2 SDK.
I've decided to use the validate<key>:error:
method to check if there is already a Managed Object with the specific value of <key>
. An error is raised if this is the case.
For example:
- (BOOL)validateMyAttribute:(id *)value error:(NSError **)error { // Return NO if there is already an object with a myAtribute of value }
Thanks to Martin Cote for his input.
When querying, make sure you use
self.managedObjectContext
, to ensure you check for duplicate's existence in correctmanagedObjectContext
. Otherwise, Save As (that is, migration to new url) will fail.Performing a fetch will change the object graph in the managed object context - which is not something you want to do inside a validation method!
not necessarily - if you only query but not insert/update/delete any entity, the context will not get dirty by the validation. It is not recommended to introduce edits (to dirty your context) in validations, because it causes recursion - still in some situations it is OK.
You could optimize by checking if previously saved and field not changed.