CoreDataTableView Not Updating When Saving From Child ManagedObjectContext and Parent ManagedObjectContext

孤者浪人 提交于 2019-12-11 19:22:07

问题


I'm trying to populate CoreData from a JSON file with thousands of entries. What I'm trying to do is create a new NSManagedObjectContext with the parent property set to my main NSManagedObjectContext. Every so often I save on my child context and if successful then save on my main context. If that's also successful I try to reload my tableview. My CoreDataTableView is setup with an NSFetchedResultController and taken directly from Apple's documentation. However, the table view isn't refreshed. Does anyone have any suggestions?

#pragma mark - Setters

- (void)setManagedObjectContext:(NSManagedObjectContext *)managedObjectContext
{
    _managedObjectContext = managedObjectContext;
    if (managedObjectContext) {
        NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Place"];
        request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"location" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]];
        request.predicate = nil; //Fetch all Tags
        self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                        managedObjectContext:managedObjectContext
                                                                          sectionNameKeyPath:@"group"
                                                                                   cacheName:nil];
    }
}


#pragma mark - View Lifecycle

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if (!self.managedObjectContext) {
        [self setupDocument];
    }
}

- (void)parseList
{
    dispatch_queue_t jsonParsing = dispatch_queue_create("json parsing", NULL);
    dispatch_async(jsonParsing, ^{
        //omitted for brevity
        NSArray *places = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&parseError];
        NSManagedObjectContext *childContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
        childContext.parentContext = self.managedObjectContext;
        int placesCount = [places count];

        [childContext performBlock:^{
            int count = 0;
            for (NSDictionary *place in places)
            {
               //omitted for brevity. Calls a category on my Place NSManagedObjectSubclass passing in the child context

                count++;

                if (count % 1000 == 0 || count == placesCount) {
                    NSError *error;
                    if ([childContext save:&error]) {
                        NSLog(@"Saved On Child Context");
                        [self.managedObjectContext performBlock:^{
                            NSError *mainError;
                            if ([self.managedObjectContext save:&mainError]) {
                                NSLog(@"Saved On on Parent Context");
                                [self.tableView reloadData];
                            }
                        }]; //End of ManagedObject Block
                    }
                }
            }
        }]; //End of ChildContext Block

    }); //End of Json Parsing Block
}

- (void)setupDocument
{
    NSURL *filePath = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    filePath = [filePath URLByAppendingPathComponent:@"Document"];
    UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:filePath];

    //Create if it doesn't exist
    if (![[NSFileManager defaultManager] fileExistsAtPath:[filePath path]]) {

        //Async save
        [document saveToURL:filePath forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
            if (success) {
                self.managedObjectContext = document.managedObjectContext;
                [self parseList];
            }
        }];
    } else if (document.documentState == UIDocumentStateClosed){
        [document openWithCompletionHandler:^(BOOL success){

            //Open it, don't need to refetch stuff
            if (success) {
                self.managedObjectContext = document.managedObjectContext;
            }
        }];
    } else {
        //else use it the managed context
        self.managedObjectContext = document.managedObjectContext;
    }
}

回答1:


Is the data being saved off? If the data is actually saving but the table isn't reflecting that try this:

[tableView reloadData]



回答2:


I believe this code needs to be executed on the main thread...

[self.managedObjectContext performBlock:^{
    NSError *mainError;
    if ([self.managedObjectContext save:&mainError]) {
        NSLog(@"Saved On on Parent Context");
        [self.tableView reloadData];
    }
}]; //End of ManagedObject Block


Try wrapping it in a:
dispatch_async(dispatch_get_main_queue(), ^{
}


来源:https://stackoverflow.com/questions/17031288/coredatatableview-not-updating-when-saving-from-child-managedobjectcontext-and-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!