Is initializing the Core Data stack in a background thread a good design choice?

| | August 8, 2015

Hi fellow Stackoverflow users,

I am trying to optimize my iphone application startup time (i.e make the first view appear as soon as possible once the app is open). The section I want to optimize is the initialization of the Core Data stack (managed object context, persistent store coordinatorm, etc…) in the application delegate. I thought of two ways to solve this problem and wonder what are you thoughts(pros/cons) on those solutions (or other you may have) ?

Note: The Core Data Stack is initialized in the application delegate for the reasons given in Where to place the "Core Data Stack" in a Cocoa/Cocoa Touch application

Solution 1 (my prefered one):

Initialize the Core Data Stack in a background thread from the application delegate. This will allow the application initialization to be faster and the window/view to be displayed sooner.

Solution 2:

Lazy instantiate the Core Data Stack when a view controller requires access to the Core Data Stack. I like this idea however, the Core Data Stack should be initialized in the application delegate and then be passed on in each view controller which requires it.

Note: This solution breaks the convention of initializing the Core Data Stack in the application delegate.


One Response to “Is initializing the Core Data stack in a background thread a good design choice?”

  1. If you look at the standard Core Data utilizing templates, you will see that the stack is not initialized until some view controller calls for the managedObjectContext of the app delegate. So, the Core Data stack does not initialize until after a view requiring the managedObjectContext loads and begins to configure itself.

    The actual initialization of the stack is very lightweight and quick. Core Data doesn’t do much until you start actively generating the object graph and reading and writing to persistent store. Simply initializing the stack takes very, very little time.

    Sometime back I had similar concerns and did some test. I found out that the real lag in start ups is the loading of the first view, regardless of whether it used Core Data or not. I wasn’t able to measure any differences in startup time between having Core Data enabled and having it disabled.

    So, I wouldn’t bother with a non-standard initialization unless your own custom testing shows it causes some performance drag.

Leave a Reply