问题描述
我的应用程式已设定好,以便在第一次使用时,从基于网路的xml资讯提供中下载所需的资料。
My app is setup so that when it's first used, it downloads the required data from a web based xml feed.
使用者也可以定期更新
当这样做时,我要删除现有的数据库,然后通过我在第一次加载时使用的代码重新创建它。
When they do this, I want to delete the existing database and then recreate it via the code I use for the first load.
我读到简单地删除数据库不是正确的方法,所以我使用下面的方式来销毁数据,然后加载新的数据集。
I read that simply deleting the database is not the correct way to do this so I'm using the following to destroy the data before loading the new dataset.
- (void)resetApplicationModel {
NSURL *_storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: DBSTORE]];
NSPersistentStore *_store = [persistentStoreCoordinator persistentStoreForURL:_storeURL];
[persistentStoreCoordinator removePersistentStore:_store error:nil];
[[NSFileManager defaultManager] removeItemAtPath:_storeURL.path error:nil];
[persistentStoreCoordinator release], persistentStoreCoordinator = nil;
}
但这不起作用,当执行数据刷新时,数据,但无法将其保存到数据库,并在控制台中生成以下错误:
However this doesn't work, when performing a data refresh, it downloads the data but can't save it to the database and generates the following error in the console;
此NSPersistentStoreCoordinator没有持久存储。
This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.
刷新资料库的「正确」方法是什么?
What's the "correct" way to refresh a database?
推荐答案
这样做的正确方法是只取出所有对象,删除它们,然后保存上下文。 (http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html)
The "right" way to do this is to just fetch all of the objects, delete each of them, and then save the context. (http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html)
- (void) deleteAllEntitiesForName:(NSString*)entityName {
NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:entityName inManagedObjectContext:moc];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSError *error = nil;
NSArray *array = [moc executeFetchRequest:request error:&error];
if (array != nil) {
for(NSManagedObject *managedObject in array) {
[moc deleteObject:managedObject];
}
error = nil;
[moc save:&error];
}
}
。
这篇关于正确的方法来刷新Core Data数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!