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

前端 未结 5 1343
温柔的废话
温柔的废话 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:52

    Let me put the best approach from Apple Sample code itself. Please refer the sample code "ThreadedCoreData" for more info.

    https://developer.apple.com/library/content/samplecode/ThreadedCoreData/Introduction/Intro.html

        // before adding the earthquake, first check if there's a duplicate in the backing store
        NSError *error = nil;
        Earthquake *earthquake = nil;
        for (earthquake in earthquakes) {
            fetchRequest.predicate = [NSPredicate predicateWithFormat:@"location = %@ AND date = %@", earthquake.location, earthquake.date];
    
            NSArray *fetchedItems = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
            if (fetchedItems.count == 0) {
                // we found no duplicate earthquakes, so insert this new one
                [self.managedObjectContext insertObject:earthquake];
            }
        }
    

提交回复
热议问题