尔加!试图重置核心数据。每隔一次工作?

时间:2012-03-26 15:59:47

标签: ios core-data nsmanagedobjectcontext

好吧,所以我的app delegate创建了所有Core Data的东西,然后发送给我的第一个视图控制器。

我的第一个视图控制器是一个NSURLConnectionDelegate ...在connectionDidFinishLoading方法中,我想删除persistentStore并重新创建它...然后从XML文件中解析/重新填充它。

这是我的connectionDidFinishLoading代码:

-(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];
}  
}

我知道这里有什么问题......只是无法弄清楚是什么。它每次我构建/运行时都会工作。当我尝试在我的解析器方法中保存managedObjectContext时出现错误

任何人都可以提供有关如何解决此问题的示例代码吗?

提前致谢,

1 个答案:

答案 0 :(得分:1)

我能够让这个工作

(在我的视图控制器中)

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

id appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate resetCoreData];

self.managedObjectContext = [appDelegate managedObjectContext];
[self parseXML];   
}

(在我的app委托中)

- (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;

}