ObjC, Basic data: "do not allow duplicates"?

I am new to Core Data. I understand that this is an object graph manager and is different from a database. However, some functions must be performed by the programmer.

Before writing some logic that has a better and more optimized copy within coredata: is it possible to add unique keys? How entityA.name=@"jem", entityB.name=@"jem"is not not insert entityB because of the name that is already in use?

thanks :-) Jam.

+5
source share
2 answers

Apple Core Data Documentation

Core Data - , GUI, , . , - , - , :

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;
     }
}

+10

, . , :

-(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!

. ObjectiveRecord, , , .

+1

All Articles