views:

22

answers:

1

I was wondering if there is a way to share an NSManagedObject between two or more NSManagedObjectContext objects running in the same thread.

I have the following problem: I have one main context shared through all my code in the application and several different contexts that are created for each remote fetch request that I issue. (I created a custom class that fetches remotely and inserts all the objects found in the server in his own NSManagedObjectContext). Those fetch requests may run simultaneously since they use NSURLConnection objects that may end at different times. If the same remote object gets fetched by different connections, I will end up with duplicates at the moment of saving and merging the context with the main one. (That is, objects that have the same remote ID but a different objectID).

One possible solution would be to save (and so persist) every object as soon as it is created but I can't do that because it may have some relationships that may still have not been filled and won't validate during the save operation.

I'm really looking forward to a method that allows you to share the same non-persistent instance of an object between context. If anybody has encountered this issue and came up with a solution, I would be pleased to know!

+1  A: 

Context cannot communicate between each other save through their stores. However, you can insert a managed object with a nil managed object context and it will be independent (albeit without relationships) of any context. You could pass that independent managed object around however you wished and insert it into a context when you needed to persist it. This is dangerous but possible.

However, if you're not running each connection on a separate thread then you don't gain anything by having multiple context. Each connection object will activate its delegate in sequence on the main thread. In this case, your easiest solution would be to use the same delegate for all the connections and let the delegate handle the insertions into a single context. To prevent duplication, just do a fetch on the remoteID and see if you get back an extant object before inserting a new object for that remoteID.

TechZen
Thank you very much for your answer. It was really helpful. The only problem with the approach of using a single context is that I can't save it once one of the remote fetch requests has ended, since there may be other requests that have not yet fetched from the server some non-optional relationships for some objects (thus canceling the save operation). I am currently doing it this way, but the thing I want to avoid is to wait that all fetch requests are done to save and merge the objects in the main context. I guess there is no solution to this problem, since passing nil would not suffice...
Eugenio Depalo