我在使用多线程应用程序时在 Core Data 中保存数据时遇到问题。场景如下:
我有一些在后台线程中运行的 http 请求NSOperation
。当 JSON 格式的数据到达时,我尝试将这些数据保存在 Core Data 中。NSManagedObjectContext
现在,当我尝试保存它从未正确保存的数据时,我已经为每个线程创建了单独的线程。有时一半数据被保存有时没有。
任何猜测为什么这是hapaneing
+ (void) initialize {
contextfactory = [[ThreadedContext alloc] init];
}
- (id) init {
if((self = [super init])) {
}
[self setupObjectModel];
[self setupStoreCoordinator];
return self;
}
- (void) setupObjectModel {
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
}
- (NSString*) sharedDocumentsPath {
static NSString *SharedDocumentsPath = nil;
if (SharedDocumentsPath)
return SharedDocumentsPath;
// Compose a path to the <Library>/Database directory
NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
return [[libraryPath stringByAppendingPathComponent:@"Database"] retain];
}
- (NSURL *) storeUrl {
NSString * const kCoreDataSQLiteName = @"XPPS.sqlite";
// Get the paths to the SQLite file
NSString *storePath = [[self sharedDocumentsPath] stringByAppendingPathComponent:kCoreDataSQLiteName];
return [NSURL fileURLWithPath:storePath];
}
- (void) setupStoreCoordinator {
NSError *error = nil;
if(!_persistentStoreCoordinator)
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: _managedObjectModel];
[_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL: [self storeUrl] options:nil error:&error];
if(error) NSLog(@"%@", error);
}
- (NSManagedObjectContext *) createObjectContext {
NSManagedObjectContext *output = [[[NSManagedObjectContext alloc] init] autorelease];
[output setPersistentStoreCoordinator:_persistentStoreCoordinator];
return output;
}
+ (NSManagedObjectContext *) buildContext {
return [contextfactory createObjectContext];
}
+ (void) createStoreCoordinator {
[contextfactory setupStoreCoordinator];
}
+ (NSString *) storePath {
return [[contextfactory storeUrl] path];
}
这是获取每个线程的托管上下文的代码。它源自NSObject
而不是NSOperation
。猜猜我该如何解决这个问题?