views:

37

answers:

1

My application downloads and caches photos into coreData in background threads while still allowing the user to poke around in the application. Currently after a photo's data is done downloading I start a thread to save it to coredata using the suggested shared storeCoordinator and thread-owned context then merge on the main thread, I also lock the shared coordinator until just before merging. This locking causes performance issues though on reads by the user.

Do I need to lock here? What are the pitfalls of not locking? The flow is essentially:

-(void)saveThreaded:(args)args {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSThread setThreadPriority:.5];

[_appDelegate.persistentStoreCoordinator lock];  //necessary?
NSManagedObjectContext *_moc = [[NSManagedObjectContext alloc] init];
[_moc setPersistentStoreCoordinator: [_appDelegate persistentStoreCoordinator]];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(threadControllerContextDidSave:)
                                             name:NSManagedObjectContextDidSaveNotification object:_moc];
...<blah blah>...
}

- (void)threadControllerContextDidSave:(NSNotification*)saveNotification {
// need to unlock before we let main thread merge  
[_appDelegate.persistentStoreCoordinator unlock];
[self performSelectorOnMainThread:@selector(mergeToMainContext:) withObject:saveNotification waitUntilDone:YES];
}

- (void)mergeToMainContext:(NSNotification*)saveNotification {
NSError *error;
[_appDelegate.managedObjectContext mergeChangesFromContextDidSaveNotification:saveNotification];  
if (![_appDelegate.managedObjectContext save:&error]) {
<handle error>
}
}
+1  A: 

No you do not need a lock here, the NSManagedObjectContext will lock the NSPersistentStoreCoordinator and you are probably hindering that.

Marcus S. Zarra
Haha, thats great :) Thanks, I'll remove the locking!
Shizam