Core Data insert objects in NSOperation and sync

一笑奈何 提交于 2019-12-13 07:29:08

问题


I'm saving objects from network response in NSOperation. As I understand for merge MOC's changes from background threads to main I can use mergeChangesFromContextDidSaveNotification or performBlock with parent context.

What should I prefer to use mergeChangesFromContextDidSaveNotification or performBlock? What are the pros and cons of each merge method?

NSOperation executed in background context. So when I call performBlock will be created new thread or not?


回答1:


The answer depends very much on whether your background MOC has the main MOC as a parent.

You only need to use performBlock if you are using MOCs with private/main queue concurrency.

And if you are, to get commands executed in the corresponding correct queue, you'd use performBlock.

So even if you have to use mergeChanges-- and you don't have to with child contexts-- you would nest mergeChanges in a performBlock! But the reason you don't have to with a child context is because your "background thread" MOC should could be a child of the main thread MOC. So all you have to do is save the child to merge changes into the parent. (Note that the parent also needs to be saved)

So to get back to the question:

  • mergeChanges if you're not pushing changes from child to parent MOC with a save in the child
  • use performBlock everywhere but on operations on the mainQueueMOC on the main thread if you have using multiple MOCs with different concurrency types



回答2:


I'm not sure if two methods you mentioned provide equivalent functionality: you use performBlock to perform random code on the tread of the receiver managed object context. And you use mergeChangesFromContextDidSaveNotification to process NSNotification from another context save. If I got it right up to here, your only chose is the latter.

Potentially you can create a child context within NSOperation, saved data from child context propagates into parent context automatically.

To elaborate further, you would use performBlock to modify parent's managed objects from the background - it basically dispatches you to the thread of the managed object context to allow perform operations in a safe manner




回答3:


Searching answer on my question I found Concurrent Core Data Stacks Performance article. This article answer that if you user old core data stack with sync data using mergeChangesFromContextDidSaveNotification method you get better performance. Also I found apple example ThreadedCoreData. In this example they still using sync with mergeChangesFromContextDidSaveNotification.

So answer on my question is if you carry on performance you should use mergeChangesFromContextDidSaveNotification if you what simpler realization you should use nested contexts.



来源:https://stackoverflow.com/questions/23740597/core-data-insert-objects-in-nsoperation-and-sync

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