Reputation: 2550
Alright, so my app delegate creates all the Core Data stuff, and I send to my first view controller.
My first view controller is a NSURLConnectionDelegate... in the connectionDidFinishLoading method, I would like to erase the persistentStore and recreate it... and then parse/repopulate it from an XML file.
Here is my connectionDidFinishLoading code:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
//I believe I should nil out the context...
managedObjectContext = nil;
//Erase the persistent store from coordinator and also file manager.
NSError *error = nil;
NSPersistentStore *store = [self.persistentStoreCoordinator.persistentStores lastObject];
NSURL *storeURL = store.URL;
[persistentStoreCoordinator removePersistentStore:store error:&error];
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
//Make new persistent store and add to the coordinator
if (![self.persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
}
else {
//Store is readied, now recreate the managedObjectContext
id appDelegate = (id)[[UIApplication sharedApplication] delegate];
managedObjectContext = [appDelegate managedObjectContext];
//Call the parser!
[self parseXML];
}
}
I know there's something wrong here... just can't figure out what. It works every second time I Build/Run. The error comes when I attempt to save the managedObjectContext in my parser methods
Can anyone provide the sample code on how I can fix this?
Thanks in advance,
Upvotes: 1
Views: 846
Reputation: 2550
I was able to get this working
(in my view controller)
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
id appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate resetCoreData];
self.managedObjectContext = [appDelegate managedObjectContext];
[self parseXML];
}
(in my app delegate)
- (void)resetCoreData;
{
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"deleteme.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];
}
self.managedObjectContext = nil;
self.persistentStoreCoordinator = nil;
}
Upvotes: 1