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