最初にデータ モデルの複数のバージョンを作成する主な理由は、既存のデータベースを削除して変更を加えた新しいデータベースを作成するよりも、移行 (データベースのアップグレード) をよりエレガントに処理することです。
したがって、以前のデータ モデルを使用する以前に出荷されたバージョンのアプリがあり、データベースをエレガントにアップグレードする機能が必要な場合は、以前のモデルをそのままにしておきます。
データ モデルの複数のバージョンを作成した唯一の理由が、初期開発中にデータをそのまま維持することであり、以前のデータ モデルを使用したアプリを他に誰も持っていない場合は、削除してください。それは問題ではありません。
データ モデルを自動的かつエレガントに移行するには、アプリ デリゲートで次のコードを使用します。
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"database.sqlite"]; //change to the name of your database
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
NSError *error = nil;
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
//[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]; --delete old model if necessary
//abort(); --Abort App if necessary
}
return _persistentStoreCoordinator;
}