How to avoid the UI freeze while a Managed Object Context is saving?

半城伤御伤魂 提交于 2019-12-09 20:17:15

问题


I want to implement a UI-responsive downloading and parsing of a large data set, saving it with Core Data.

My setup:

I display the downloaded content in a custom view controller. I don't use a NSFetchedResultsController.

There are 3 MOCs:

  1. masterMOC (responsible for saving to disk, NSPrivateQueueConcurrencyType)
  2. mainMOC (used by UI, NSMainQueueConcurrencyType, a child of the masterMOC)
  3. backgroundMOC (responsible for the import from JSON, created in a separate thread, a child of the masterMOC)

I am importing in batches - every 50 items I perform the MOC saving in the following way:

NSError *error;
[backgroundMOC save:&error];
NSManagedObjectContext *masterMOC = backgroundMOC.parentContext; //set during initialization               
[masterMOC performBlock:^{
    NSError *parentContextError = nil;
    [masterMOC save:&parentContextError];
}];

I expect the changes in the mainMOC to be made after the masterMOC is saved. If I try to access some relationship of a random managed object while the masterMOC is saving (saving takes some time), the UI hangs until the saving is completed.

Question: how to avoid the UI freeze while the masterMOC is saving?


回答1:


Your problem probably is that the data store is blocking while you are writing to it. So, either make the data store non-blocking (this may or may not be possible in your case) or if not viable, make the accessor non-blocking. In the latter case the GUI will not hang, but it also will not update either until the result of the access comes back.



来源:https://stackoverflow.com/questions/14340617/how-to-avoid-the-ui-freeze-while-a-managed-object-context-is-saving

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