Search for duplicate values ​​in master data

I am inserting new objects into the master data database. Is there a way to check if there is a duplicate in the database before inserting values ​​into?

AccountDetails * newEntry = [NSEntityDescription insertNewObjectForEntityForName:@"AccountDetails" inManagedObjectContext:self.managedObjectContext];   
newEntry.acc_date=date;
newEntry.bank_id=bank_id1;
NSError *error;
    if (![self.managedObjectContext save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
        }       
   [self.view endEditing:YES];

every time I run the application, it inserts the values ​​again. I want to check if there is any new category in it, if not, then I will add only this new one.

thanks in advance.

+3
source share
2 answers

You can get or you can count. Counting is much faster than sampling. Depends on what you are trying to do.

If you just want to insert new ones and skip duplicates, use -[NSManagedObjectContext countForFetchRequest: error:]to determine if the object exists.

, . , , .

- :

  • NSDictionary

(), :

[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"myUnique in %@", uniqueIDArray]];

ARE . , , , , . .

+6

db check, - , , result.count > 1, DUPLICATE :

- (NSManagedObject*) findOrCreateObjectByValue:(id)value
                              propertyName:(NSString*)propertyName
                                entityName:(NSString*)entityName
                            additionalInfo:(NSDictionary*)additionalInfo
                                   context:(NSManagedObjectContext*)context
                                     error:(NSError* __autoreleasing*)error
{

NSManagedObject* res = nil;

NSFetchRequest* r = [NSFetchRequest fetchRequestWithEntityName:entityName];
[r setPredicate:[NSPredicate predicateWithFormat:@"%K == %@",propertyName,value]];

NSArray* matched = [context executeFetchRequest:r
                                          error:error];

if (matched) {
    if ([matched count] < 2) {
        res = [matched lastObject];
        if (!res) { //No existing objects found, create one
            res = [NSEntityDescription insertNewObjectForEntityForName:entityName
                                                inManagedObjectContext:context];
            [res setValue:value
                   forKey:propertyName];
        }
    } else {
        if (error) {
            *error = [NSError errorWithDomain:@"some_domain"
                                         code:9999
                                     userInfo:@{@"description" : @"duplicates found"}];
        }
    }
}

return res;

}

0

All Articles