I am having a problem in saving the data in Core Data while im multithreaded application. The scenario is the following:
I have some http requests which runs in background threads us NSOperation. When the data arrives which is in JSON I tried to save those data in Core Data.
I have created the separate NSManagedObjectContext for each thread now when I try to save the data it never saves properly. Sometime half data is saved sometime none.
Any guesses why this is 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];
}
This is the code for getting the managed context for the each thread. It is derived from NSObject and not NSOperation. Any guess how I can fix this issue?
Did you see this apple example?
Your code seems good but it is only one important think to create NSManageObject for every background thread. This example can show you how can you use the
NSManagedObjectContextDidSaveNotificationand save your data on a safe way.