I'm quite new to Core Data. My understanding is that it's an object graph manager, and that differs from a database. In that, some functionalities are to be implemented by the programmer.
Before writing some logic that has a better and more optimized counterpart in the coredata framework: Is it possible to add unique keys? Like entityA.name=@"jem", entityB.name=@"jem", fail to insert entityB due to a name already in use?
thanks :-) Jem.
Apple Core Data Documentation
Core Data is very much a database, the GUI you use to set up the entities and attributes is only part of it. I do not believe there is already functionality for rejecting non-unique keys, but you could do something like this to run a check before inserting the new entity:
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
BOOL unique = YES;
NSError  *error;
NSArray *items = [managedObjectContext executeFetchRequest:request error:&error];
if(items.count > 0){
    for(Person *thisPerson in items){
        if([thisItem.name isEqualToString: nameToEnter]){
             unique = NO;
        }
    }
}
if(unique){
     CartItem *thisItem = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.managedObjectContext];
     thisItem.name = nameToEnter;
     NSError *error;
     if (![self.managedObjectContext save:&error]) {
           return;
     }
}
and you should be good
Similar to the one above, but in the object code as a validation method. Thus we isolate it from the main code:
-(BOOL)validateForInsert:(NSError **)error {
  if (![super validateForInsert:error]) {
    NSLog(@"Validate for insert FALSE: %@", *error);
    return NO;
  }
  return [self validateConsistency:error];
}
-(BOOL)validateForUpdate:(NSError **)error {
  if (![super validateForUpdate:error]) {
    NSLog(@"Validate for update FALSE: %@", *error);
    return NO;
  }
  return [self validateConsistency:error];
}
-(BOOL)validateConsistency:(NSError **)error {
  // Count number of names
  NSArray *accounts = [Account whereFormat:@"name == '%@'", self.name];
  if ([accounts count] > 1) {
    // Error!
Note: I used ObjectiveRecord, but I trust that you know how to count your records.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With