Wednesday, February 10, 2016

Pragmatic Core Data

Florian Kugler:

Now to answer the ultimate question, how do I get best performance with Core Data? Is the question that I can un-answer in the abstract. I think that your best bet is to look at the architecture, to understand this architecture, to really see how do these different layers work. How are their performance characteristics of these layers and then reason about your app’s behavior with this background knowledge. When you do that you can make the right choice for your specific project.

[…]

The advantages of the [nested contexts] set up are that if you save stuff from the main context, for example, the scenario I mentioned before, you copy in tons of data into your app, just copy paste and then you save. Now the save doesn’t block the main thread any more. Because the save of your UI context, only pushes all this stuff down into this private context that’s below. The private context can save this later. It’s one of the major advantages, and one of the major reasons nested contexts were introduced with iOS 5, where there’s iCloud syncing stuff.

[…]

Another disadvantage is that saving a child context pushes all changes down into the parent context. So before I said when you merge change, merge save notifications, Core Data can discard stuff because it knows it is not of interest to the other context. Now, with nested context, Core Data has to channel all this data down to the store, so it has to push all of this in. So if you insert 10,000 objects in the child context, Core Data has to instantiate 10,000 objects in the parent context, even if you don’t care about them there.

[…]

Another disadvantage is that you have no merge policies. When you work with nested context, you save the child context and all the changes are pushed down into the parent context with brute force. There is no consideration about conflict resolution, this is just a brute force push down into the previous context. It just overrides. Another pretty esoteric issue is that once you work with nested contexts you have to be aware there are weird things going on with temporary and permanent object IDs, and you can run into weird situations where you can break stuff like the uniquing guarantees that Core Data usually has.

Comments RSS · Twitter

Leave a Comment