Search code examples
iosobjective-cmultithreadingcore-datansmanagedobjectcontext

Why not use a privatecontext for all Core Data operations?


In my iPhone app I am inserting lots of data after login by means of Core Data. Initially I was showing a loader while data was being inserted so the blocking of UI was not a matter, but now I removed the loader and moved all the insert operations on the background thread by changing the managedobjectcontext concurrency type to NSPrivateQueueConcurrencyType for some insertions to relieve the UI from the heavy insertion work.

I am wondering what will be the downside if I use this same context and NOT NSMainQueueConcurrencyType for all operations, is it recommended?


Solution

  • You SHOULD use NSPrivateQueueConcurrencyType for all of your contexts. NSFetchedResultsController, for example, does work fine with a private queue context as long as your observe all of the rules for using queue confinement (i.e. fetches must be performed through the queue, as well as faults, etc.). There is a bug with NSFetchedResultsController caching when using private queue contexts, but caching covers only a limited number of use cases.

    If/when you are using data from Core Data to update UI elements, you will still have to access the UI from the main queue. For example, this would be accessing a property to update a label:

    [[object managedObjectContext] performBlock:^{
        NSString *text  = [object someProperty];
        [NSOperationQueue mainQueue] addOperationWithBlock:^{
            [[self someLabel] setText:text];
        }];
    }];
    

    There are many advantages to using private queue confinement. The downside is that you will have to include code like that above - which far outweighs performing Core Data work on the main queue.