我的应用程序在后台线程中下载照片并将其缓存到coredata中,同时仍允许用户在应用程序中浏览。当前,在下载完照片的数据后,我启动一个线程,使用建议的共享存储协调器和线程拥有的上下文将其保存到coredata,然后在主线程上合并,我还锁定共享协调器,直到在合并之前。这种锁定会导致用户在读取时出现性能问题。
我需要锁在这里吗?不锁闭的陷阱是什么?该流程基本上是:
-(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>
}
}