Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to figure out what thread an NSManagedObjectContext is on?

My understanding of threads with respect to an NSManagedObjectContext is that it can only execute core data fetch requests, deletes, etc., on the thread from which it was created. Is there any way to check to see what thread an NSManagedObjectContext was created on, or if at a particular point of execution the current thread is that of a particular NSManagedObjectContext?

Thanks!

like image 847
Mason Avatar asked Sep 06 '25 05:09

Mason


2 Answers

My understanding of threads with respect to an NSManagedObjectContext is that it can only execute core data fetch requests, deletes, etc., on the thread from which it was created.

That's not really accurate. It would be better to say that contexts cannot be used concurrently by more than one thread or queue. A common approach to dealing with this is to create different contexts for each thread/queue. It's also possible to use the performBlock and performBlockAndWait methods to use contexts on multiple threads while keeping context access effectively single-threaded.

As a result, contexts don't have any notion of belonging to a thread or queue, nor do threads have any reference to contexts that were created on them.

If you follow the approach of one context per thread or queue, you need to keep track of where code will run and use the appropriate context. For example when using GCD, create a context for a specific dispatch queue, and only use it when you've used something like dispatch_async to run on that queue.

If you really want to link a context with a queue, you could use your own data structure to look up contexts from whatever concurrency scheme you're using-- by the current NSOperationQueue, or dispatch queue, or NSThread, or whatever. This is rarely needed, but it's a possibility if you can't find better techniques.

like image 103
Tom Harrington Avatar answered Sep 10 '25 11:09

Tom Harrington


As far as I know you can't. At least not too easily. Why? Use -performBlock: - it will perform all requests on the correct thread.

like image 41
Mario Avatar answered Sep 10 '25 13:09

Mario