I have been trying to add objects in core data. So, i want that it should not allow duplicate entries in core data store. How to do that? This is my code related to save data.
-(IBAction)save:(id)sender
{
if([name.text isEqualToString:@""] && [address.text isEqualToString:@""] && [phone.text isEqualToString:@""])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Yo..!"
message:@"Data Not Saved"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}
else
{
coreDataAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *newContact;
newContact = [NSEntityDescription
insertNewObjectForEntityForName:@"Contacts"
inManagedObjectContext:context];
[newContact setValue:name.text forKey:@"name"];
[newContact setValue:address.text forKey:@"address"];
[newContact setValue:phone.text forKey:@"phone"];
name.text = @"";
address.text = @"";
phone.text = @"";
NSError *error;
[context save:&error];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Yo..!"
message:@"Data Saved"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
NSLog(@"Object Saved\n");
}
}
As there is no built in method available, you need to fetch results and check whether result contains object you don't want to be duplicated.
Here is code snippet:
-(void)checkForDuplicates
{
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Students"
inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"students"
ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[request setSortDescriptors:sortDescriptors];
[sortDescriptor release];
NSError *Fetcherror;
NSMutableArray *mutableFetchResults = [[managedObjectContext
executeFetchRequest:request error:&Fetcherror] mutableCopy];
if (!mutableFetchResults) {
// error handling code.
}
if ([[mutableFetchResults valueForKey:@"users"]
containsObject:name.text]) {
//notify duplicates
return;
}
else
{
//write your code to add data
}
}
Hope this may help you!
no, coredata has no built-in in uniquing as it isn't a DB.
you have to assure uniqueness in your program logic.
e.g. often, one does a fetch for an entry that should be unique and if that fetch has 1 entry, don't add another, else add it!
==> this works well for serial CD access, but can get complicated with multiple contexts that run in a multithreaded env
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