Generic approach to NSManagedObjectContext in multi-threaded application Generic approach to NSManagedObjectContext in multi-threaded application multithreading multithreading

Generic approach to NSManagedObjectContext in multi-threaded application


A year after posting this question I finally built a framework to generalize and simplify my working with Core Data. It goes beyond the original question, and adds a number of features to make Core Data interactions much easier. Details here: https://github.com/chriscdn/RHManagedObject


I found a solution after finally understanding the problem better. My solution doesn't directly address the question above, but does address the problem of why I had to deal with threads in the first place.

My application uses the ASIHTTPRequest library for asynchronous requests. I fetch some data from the server, and use the delegate requestFinished function to add/modify/delete my core-data objects. The requestFinished function was running in a different thread, and I assumed this was a natural side-effect of asynchronous requests.

After digging deeper I found that ASIHTTPRequest deliberately runs the request in a separate thread, but can be overridden in my subclass of ASIHTTPRequest:

+(NSThread *)threadForRequest:(ASIHTTPRequest *)request {    return [NSThread mainThread];}

This small change puts requestFinished in the main thread, which has eliminated my need to care about threads in my application.