开发者

Correct way to refresh Core Data database

My app is setup so that when it's first used, it downloads the required data from a web based xml feed.

The user also has the option to periodically refresh the data via a setting.

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 t开发者_运维百科o 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;

This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation.

What's the "correct" way to refresh a database?


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

}

Then you can just recreate your objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜