I have a Core Data model which works well importing and exporting data. The way my app works is that it downloads a JSON file from the database, parses it, flushes out the core data model, then adds the data again (effectively a refresh of the local data model).
If I make a change to the database, the change is reflected in the JSON file, but is not reflected in the core data model until I restart (aka end the app, open again) the app.
Im sure it must be something to do with the way I am flushing out the database, but I just can’t put my finger on it. I’ve included some code below to help.
The method I’m using to flush out the data model:
- (void)resetCoreData;
{
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"AppWithCoreData.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtURL:storeURL error:NULL];
NSError* error = nil;
if([fileManager fileExistsAtPath:[NSString stringWithContentsOfURL:storeURL encoding:NSASCIIStringEncoding error:&error]])
{
[fileManager removeItemAtURL:storeURL error:nil];
}
persistentStoreCoordinator = nil;
managedObjectContext = nil;
[self managedObjectContext]; // Rebuild Object Context
}
One line of the code I’m using to add the data to the data model:
[model setValue:[dictionary objectForKey:@"eventID"] forKey:@"eventID"];
Usually when you need to save your changes to your core data store you need to save them.
To achieve it you need to call
In this manner changes you have performed are saved to disk. In fact when you simply change, for example, the value of an attribute on a specific entity, it’s only available in memory.
I suppose the changes are available only at the next restart since in your app delegate you listen for
applicationWillTerminatedelegate and there you save the context. Are you using the Core Data Stack provided with Xcode template?If possible provide more details, maybe I could help you.
Hope that helps.