Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multithreaded use of Core Data (NSOperationQueue and NSManagedObjectContext)

In Apple's Core Data documentation for Concurrency with Core Data, they list the preferred method for thread safety as using a seperate NSManagedObjectContext per thread, with a shared NSPersistentStoreCoordinator.

If I have a number of NSOperations running one after the other on an NSOperationQueue, will there be a large overhead creating the context with each task?

With the NSOperationQueue having a max concurrent operation count of 1, many of my operations will be using the same thread. Can I use the thread dictionary to create one NSManagedObjectContext per thread? If I do so, will I have problems cleaning up my contexts later?

What’s the correct way to use Core Data in this instance?

like image 227
Douglas Mayle Avatar asked Sep 21 '09 13:09

Douglas Mayle


People also ask

Can we do multithreading with Core Data?

Core Data is designed to work in a multithreaded environment. However, not every object under the Core Data framework is thread safe. To use Core Data in a multithreaded environment, ensure that: Managed object contexts are bound to the thread (queue) that they are associated with upon initialization.

What are concurrency type in Core Data?

Concurrency is the ability to work with the data on more than one queue at the same time. If you choose to use concurrency with Core Data, you also need to consider the application environment. For the most part, AppKit and UIKit are not thread-safe.

What is NSManagedObjectContext?

An object space to manipulate and track changes to managed objects.

What is Persistentcontainer in Core Data?

NSPersistentContainer simplifies the creation and management of the Core Data stack by handling the creation of the managed object model ( NSManagedObjectModel ), persistent store coordinator ( NSPersistentStoreCoordinator ), and the managed object context ( NSManagedObjectContext ).


1 Answers

The correct way to use Core Data in this case is to create a separate NSManagedObjectContext per operation or to have a single context which you lock (via -[NSManagedObjectContext lock] before use and -[NSManagedObjectContext unlock] after use). The locked approach might make sense if the operations are serial and there are no other threads using the context.

Which approach to use is an empirical question that can't be asnwered without data. There are too many variables to have a general rule. Hard numbers from performance testing are the only way to make an informed decision.

like image 120
Barry Wark Avatar answered Sep 21 '22 17:09

Barry Wark