Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 7th, 2012  |  syntax: None  |  size: 1.00 KB  |  hits: 22  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How do I make a custom validation (for uniqueness) in Core Data?
  2. -(BOOL)validateValue:(__autoreleasing id *)value forKey:(NSString *)key error:(NSError *__autoreleasing *)error {
  3.     [super validateValue:value forKey:key error:error];
  4.  
  5.     // Validate uniqueness of my_unique_id
  6.     if([key isEqualToString:@"my_unique_id"]) {
  7.         NSFetchRequest * fetch = [[NSFetchRequest alloc] init];
  8.         [fetch setEntity:[NSEntityDescription entityForName:[self.entity name]
  9.                inManagedObjectContext:self.managedObjectContext]];
  10.  
  11.         NSPredicate *predicate = [NSPredicate
  12.             predicateWithFormat:@"my_unique_id = %@",[self valueForKey:key]];
  13.  
  14.         fetch.predicate = predicate;
  15.  
  16.         NSError *error = nil;
  17.         NSUInteger count = [self.managedObjectContext
  18.                            countForFetchRequest:fetch error:&error];
  19.  
  20.         if (count > 1) {
  21.             // Produce error message...
  22.  
  23.             // Failed validation:
  24.             return NO;
  25.         }
  26.  
  27.  
  28.     }
  29.  
  30.     return YES;
  31. }