Core Data saving objects in background issue

前端 未结 3 1880
离开以前
离开以前 2021-01-31 12:55

What I\'m trying todo in a nutshell is I am using a background queue to save JSON objects pulled from a web service to the Core Data Sqlite3 database. The saving takes place on

3条回答
  •  梦谈多话
    2021-01-31 13:22

    in your case because your writing to the background moc the notification for mergeChangesFromContextDidSaveNotification will come in on the background moc, not the foreground moc.

    so you'll need to register for notifications on the background thread coming to the background moc object.

    when you receive that call you can send a message to the main thread moc to mergeChangesFromContextDidSaveNotification.

    andrew

    update: here's a sample that should work

        //register for this on the background thread
        NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
        [nc addObserver:self selector:@selector(mergeChanges:) name:NSManagedObjectContextDidSaveNotification object:backgroundMOC];
    
    - (void)mergeChanges:(NSNotification *)notification {
        NSManagedObjectContext *mainThreadMOC = [singleton managedObjectContext];
    
        //this tells the main thread moc to run on the main thread, and merge in the changes there
        [mainThreadMOC performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:) withObject:notification waitUntilDone:YES];
    }
    

提交回复
热议问题