代码之家  ›  专栏  ›  技术社区  ›  Dimitris

当模型更改时,擦除用coredata存储的所有数据

  •  9
  • Dimitris  · 技术社区  · 16 年前

    我有一个应用程序可以从互联网上获取数据,并使用coredata将其存储在设备中,以获得更流畅的体验。

    因为我使用核心数据,所以每次我的模式更改时,当我尝试用存储在设备上的以前数据运行应用程序时,它都会崩溃。检测这一变化并清除设备中所有数据的最快方法是什么,因为我不介意重新加载所有数据。它比崩溃和将模式重新映射到新模式(在我的例子中)要好。

    我看到这个检查是在getter中执行的:

    - (NSPersistentStoreCoordinator *)persistentStoreCoordinator
    

    所以我只需要知道如何实现擦除整个数据库和重新设置核心数据的方法。 谢谢)

    1 回复  |  直到 16 年前
        1
  •  14
  •   Dimitris    16 年前

    回到这个问题,为了从我的coredata存储中删除所有数据,我决定简单地删除sqlite数据库文件。所以我刚刚实施了 NSPersistentStoreCoordinator 这样地:

    - (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    
        if (persistentStoreCoordinator != nil) {
            return persistentStoreCoordinator;
        }
    
        NSURL *storeUrl = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"myAppName.sqlite"]];
    
        NSError *error = nil;
        persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
        if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
    
            NSLog(@"Error opening the database. Deleting the file and trying again.");
    
            //delete the sqlite file and try again
            [[NSFileManager defaultManager] removeItemAtPath:storeUrl.path error:nil];
            if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
                NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
                abort();
            }
    
            //if the app did not quit, show the alert to inform the users that the data have been deleted
            UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Error encountered while reading the database. Please allow all the data to download again." message:@"" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
            [alert show];
        }
    
        return persistentStoreCoordinator;
    }