Is there any way we can restrict duplicate entries in core data?

前端 未结 5 1348
温柔的废话
温柔的废话 2021-02-03 14:30

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.

5条回答
  •  花落未央
    2021-02-03 14:55

    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!

提交回复
热议问题