How to prevent Core Data making duplicates in iOS 5?

后端 未结 2 467
独厮守ぢ
独厮守ぢ 2020-12-31 15:12

I\'ve run into a problem.

Over the weekend I\'ve been working on a project where I\'m pulling a large xml from a webservice.

It basically has 3 tiers - Clien

2条回答
  •  半阙折子戏
    2020-12-31 15:54

    As Stated in Apple Docs https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdImporting.html

    You need to loop the data model and handle it from there like this

    Example:

    // loop over employeeIDs
    // anID = ... each employeeID in turn
    // within body of loop
    
    NSString *predicateString = [NSString stringWithFormat: @"employeeID == %@", anID];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
    

    Personally I do not like this method and I wrote this snippet of code that handles this in a pro-efficient manor and which is straight forward! I noticed with Apples method I ran into issues with strings having different characters such as capitol letters and spaces. Below code is tested and working if you rename all your corresponding objects correctly I honestly believe this is the most efficient way to accomplish not adding duplicates in core data.

    -(void)AvoidDuplicatesinDataModel
    {
        // Define our table/entity to use
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Users"
                                                  inManagedObjectContext:managedObjectContext];
    
        // Setup the fetch request
        NSFetchRequest *request = [[NSFetchRequest alloc] init];
        [request setEntity:entity];
    
        // Define how we will sort the records
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"users"
                                                                       ascending:NO];
        NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    
        [request setSortDescriptors:sortDescriptors];
        [sortDescriptor release];
    
        // Fetch the records and handle an error
        NSError *Fetcherror;
        NSMutableArray *mutableFetchResults = [[managedObjectContext
                                                executeFetchRequest:request error:&Fetcherror] mutableCopy];
    
        if (!mutableFetchResults) {
            // Handle the error.
            // This is a serious error
        }
    
        //here usersNameTextField.text can be any (id) string that you are searching for
        if ([[mutableFetchResults valueForKey:@"users"]
             containsObject:usernameTextField.text]) {
            //Alert user or handle your duplicate methods from here
            return;
        }
    }
    

提交回复
热议问题