Core Data was mutated while being enumerated

前端 未结 1 1626
南方客
南方客 2021-01-14 08:08

I\'ve an annoying problem with Core Data. My app need to get contacts from iPhone and save it in my database. I\'m trying to do that in background thread.

I

相关标签:
1条回答
  • 2021-01-14 08:24

    This error happen when you are modifying core data while you try to get them.

    That also could be cause of the loop you're doing, you are inserting a new object in coredata without saving before you do an other retrieve. Try saving your managedobjectcontext :

    favorite I have an annoying problem with Core Data. My app need to get contacts from iPhone and save it in my database. I'am trying to do that in background thread.

    I use above code for that:

    [self performSelectorInBackground:@selector(fetchingContact) withObject:nil];
    
    
    -(void)fetchingContact{
    // Some Code
    for (int i = 0; i < nPeople; i++)
    {
    //Some Code
        NSManagedObjectContext *context = [APP_DELEGATE managedObjectContext];
        ABRecordID recordID = ABRecordGetRecordID(person);
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Contact" inManagedObjectContext:context];
        [fetchRequest setEntity:entity];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"(contactId = '%d')",recordID]];
        [fetchRequest setPredicate:predicate];
        NSError *error = nil;
        NSArray *contactObjArray = [context executeFetchRequest:fetchRequest error:&error];
        if (error) {}
        Contact *contacts;
        if (contactObjArray.count == 0) {
            contacts = [NSEntityDescription insertNewObjectForEntityForName:@"Contact" inManagedObjectContext:context];
            [context save:&error];
        }else {
            contacts = [contactObjArray objectAtIndex:0];
        }
    //Some Code
    }
    }
    

    If that doesn't solve your problem, maybe check if your method is called multiple times.

    0 讨论(0)
提交回复
热议问题