views:

233

answers:

2

I have a application that combines threading and CoreData. I and using one global NSPersistentStoreCoordinator and a main NSManagedObjectContextModel.

I have a process where I have to download 9 files simultaneously, so I created an object to handle the download (each individual download has its own object) and save it to the persistentStoreCoordinator. In the [NSURLConnection connectionDidFinishLoading:] method, I created a new NSManagedObject and attempt to save the data (which will also merge it with the main managedObjectContext).

I think that it is failing due to multiple process trying to save to the persistentStoreCoordinator at the same time as the downloads are finishing around the same time. What is the easiest way to eliminate this error and still download the files independently?

Thank you!

A: 

Just make a functon. that will save your data in an @synchronized block on context

-(void) saveObj:(NSManagedObject *) inContext:(NSManagedObjectContext *) ctx {

  @synchronized(ctx) { // Only one thread that uses 'ctx' can enter this block at the same time 
    // save data here 
  }
}

Multithreading guide

tt.Kilew
Since the OP is using multiple `NSManagedObjectContext` instances against a single `NSPersistentStoreCoordinator`, your locking suggestion will do nothing. In addition, this suggestion is never the right answer because using a single `NSManagedObjectContext` across multiple threads is always incorrect.
Marcus S. Zarra
+1  A: 

The NSManagedObjectContext instances know how to lock the NSPersistentStoreCoordinator. Since you are already using one NSManagedObjectContext per thread that is most likely not the issue.

It would help to know what the error is that you are getting. Unroll the NSError and look at its -userInfo. If the userInfo is an array then loop over the array and look at the errors inside. That will help to determine what is going on.

It is quite possible that the error can be something as simple as validation or a missing required value and has nothing to do with the actual threading.

Marcus S. Zarra