
Untitled
By: a guest on
May 7th, 2012 | syntax:
None | size: 1.00 KB | hits: 22 | expires: Never
How do I make a custom validation (for uniqueness) in Core Data?
-(BOOL)validateValue:(__autoreleasing id *)value forKey:(NSString *)key error:(NSError *__autoreleasing *)error {
[super validateValue:value forKey:key error:error];
// Validate uniqueness of my_unique_id
if([key isEqualToString:@"my_unique_id"]) {
NSFetchRequest * fetch = [[NSFetchRequest alloc] init];
[fetch setEntity:[NSEntityDescription entityForName:[self.entity name]
inManagedObjectContext:self.managedObjectContext]];
NSPredicate *predicate = [NSPredicate
predicateWithFormat:@"my_unique_id = %@",[self valueForKey:key]];
fetch.predicate = predicate;
NSError *error = nil;
NSUInteger count = [self.managedObjectContext
countForFetchRequest:fetch error:&error];
if (count > 1) {
// Produce error message...
// Failed validation:
return NO;
}
}
return YES;
}