开发者

Working with Multiple Managed Object Contexts Questions

开发者 https://www.devze.com 2023-03-20 03:35 出处:网络
I currently do multiple network requests via several threads executing in parallel, thus have a managed object context for each thread, and each thread sets attribute values for Core Data entities. So

I currently do multiple network requests via several threads executing in parallel, thus have a managed object context for each thread, and each thread sets attribute values for Core Data entities. So here is the dilemma, each network request gets small amounts of data at a time, and there are hundreds (or even thousands) of these requests, and I wish to perform saves after all network operations have occurred (so that I can safely assume that sa开发者_JAVA技巧ved data means that everything was successfully downloaded and written to store). So two questions:

  1. Do I save each managed object context after each thread is done writing to the context, or do I store all managed object contexts in memory, and at the end cycle through all of them and perform saves? (After writing this out, it became obvious that saving on the go would be the more efficient method, but I would still like to hear your thoughts.)
  2. Is there any way to merge managed object contexts without performing a save operation? I am currently merging contexts via the NSManagedObjectContextDidSaveNotification notification and was wondering if there is another way.


I don't see how you can "store all managed object contexts in memory, and at the end cycle through all of them and perform saves". Each MOC should be confined to the thread where it's created, therefore I don't see how you can effectively cycle through all MOCs without breaking this confinement rule... But you probably realized that already...

I also believe that merging MOCs via the NSManagedObjectContextDidSaveNotification is the most efficient method. I would even argue that it's easiest to save the MOCs after each object insert (e.g. when you import data). That way you minimize the scope of each merge! And since merges are performed in memory, there is little overhead in them being more granular.


You can create an controller class for all the threads and use only one Managed context to save your data.

After an thread finish download call an delegate in your ThreadControlerClass merge the data with your old data and then save when all the thread finish download. If your data is too big you can do some intermediate saves.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号