Josh Kahane
Josh Kahane

Reputation: 17169

Duplicate Names in CoreData?

In my CoreData object, I have a name attribute, just a string. Is there any automated method or boxes I can tick to stop the user saving a two objects with identical 'name' attributes? Or shall I just check this manually?

Thanks.

Upvotes: 4

Views: 408

Answers (2)

Caleb
Caleb

Reputation: 125037

Use key value validation (KVV). Add a -validateName:error: method to your entity's class. In that method, you can perform a fetch for objects with the same name. If you find any, then the entered name won't be unique in the data store, so return an error.

Upvotes: 3

rohan-patel
rohan-patel

Reputation: 5782

Unfortunately you do not have any check box or automated system to prevent duplicate data in Core data. So you gotta take care of it yourself only.. Its easy to implement.

You have to use NSPredicate combined with fetchedResultsController to perform a search whether the name already exists or not. If the name you entered is already present then your fetchedResultsController.fetchedObjects count is going to be greater than zero so you do not allow the duplicate entry. If no duplicate entry found fetchedResultsController.fetchedObjects is <1 so you will allow entry. Try code something like this:

  - (IBAction)saveName
  {
    NSLog(@"saveArtistInformation");
    NSError *error = nil;

  // We use an NSPredicate combined with the fetchedResultsController to perform the search
if (self.nameText.text !=nil)
{
    NSPredicate *predicate =[NSPredicate predicateWithFormat:@"name contains[cd] %@", self.nameText.text];
    [fetchedResultsController.fetchRequest setPredicate:predicate];
}

if (![[self fetchedResultsController] performFetch:&error])
{
    // Handle error
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    exit(-1);  // Fail
}

// compare `fetchedResultsController`'s count if its <1 allow insertion

if ([fetchedResultsController.fetchedObjects count] < 1)
{
    NSLog(@"Found that Artist already in Core Data");
    Entity *entity = (Entity *)[NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:self.managedObjectContext];
    entity.name = self.nameText.text;

    //call save method

    if (![managedObjectContext save:&error])
    {
        NSLog(@"Problem saving: %@", [error localizedDescription]);
    }
}
else
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Name  already exists" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
    [alert release];
}

Courtesy : TheAppCodeBlog

Upvotes: 2

Related Questions