核心数据,线程保存到持久存储而不锁定,什么可能出错?

时间:2010-04-08 15:23:12

标签: iphone multithreading xcode core-data

我的应用程序在后台线程中下载并缓存照片到coreData,同时仍允许用户在应用程序中浏览。目前,在完成照片的数据下载后,我开始使用建议的共享storeCoordinator和线程拥有的上下文将其保存到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>
}
}

1 个答案:

答案 0 :(得分:1)

不,你不需要锁定,NSManagedObjectContext将锁定NSPersistentStoreCoordinator,你可能会阻止它。