Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a custom validation (for uniqueness) in Core Data?

I have an entity in Core Data which has an attribute that needs to be unique. There's no way to set this in the visual interface. I assume I need to create a custom class that inherits from NSManagedObject and then write my own validation method.

I successfully created the custom class by selecting the entities in the visual editor and choosing File -> New -> New File -> NSManagedObject subclass. I use this to add creation timestamps, so I know it works.

But now what? Which methods do I need?

The NSManagedObject reference guide tells me to "implement methods of the form validate:error:" but doesn't provide an example.

Similar questions here and here, but I need a bit more help.

A complete example would be awesome, but any help is much appreciated.

like image 876
Sjors Provoost Avatar asked Jan 17 '12 07:01

Sjors Provoost


1 Answers

Let's say you have a property foo that you want to validate

From Property-Level Validation :

If you want to implement logic in addition to the constraints you provide in the managed object model, you should not override validateValue:forKey:error:. Instead you should implement methods of the form validate<Key>:error:.

Where <Key> is your property. You would actually implement something like:

-(BOOL)validateFoo:(id *)ioValue error:(NSError **)outError {
    return [self isUnique];
}
like image 197
quellish Avatar answered Oct 19 '22 16:10

quellish