Multiple contexts in the main thread: why and when

2019-02-28 15:55发布

I'm looking for a simple answer that could highlight rules for using (or avoiding) multiple contexts within the same thread (the main one in my case).

Usually, in Core Data, I set up a single main context that is used throughout the application. Then, if I need to perform some background work, I create a context for each background operation I run.

Such an approach is valid most of the time. Core Data manages the memory in a perfect manner. But I can also decide to purge some of the object graph (managing the memory footprint) explicitly. Here, I can rely on - (void)refreshObject:(NSManagedObject *)object mergeChanges:(BOOL)flag passing it to NO param. But, I need to be careful for pending changes that could be lost.

Now, my question is the following. Is there any rule of thumb that allow to decide the number of contexts that I could use within a single thread (main thread)? My thought is the following. Create a main context (where changes are saved) and additional contexts that are used only for display purposes and are created on demand. When I've finished to use one, I could just send a reset to recycle the overall memory.

Any advice? If there are any implications with new iOS 5 APIs, please share.

1条回答
Deceive 欺骗
2楼-- · 2019-02-28 16:05

flexaddicted,

Main thread contexts are most useful for scratchpad work and managing your working set.

Scratchpad work is using the MOC to process data you don't intend to -save:. Or to set up things for the undo manager. I find this of less value than you might think.

If your UI is going to display a bunch of objects that are not used in the rest of your UI, then you can manage memory by using the new MOC and then disposing of it when you dismiss the view. This allows all of those items that have no utility to the rest of your app to be disposed. While this can be useful to manage memory, it isn't a substitute for responding to the memory warnings in iOS to trim your tree.

Andrew

查看更多
登录 后发表回答