方法があり、この方法は自動軽量移行と呼ばれます。オブジェクトモデルを変更するときは、コード変更と追加の手順が必要です。
コードの場合、永続ストアコーディネーターを初期化するメソッドに2つのオプションを追加する必要があります。このようなもの:
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
if (persistentStoreCoordinator_ != nil) {
return persistentStoreCoordinator_;
}
NSString *storePath = [AppDelegate_Shared coredataDatabasePath];
NSURL *storeURL = [NSURL fileURLWithPath:storePath];
// important part starts here
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]) {
// and ends here
LogError(@"Unresolved error %@, %@", error, [error userInfo]);
// Do something
}
return persistentStoreCoordinator_;
}
モデルを変更する場合は、変更を行う前にモデルバージョンを作成する必要があります。
データモデルを選択し、メインメニューに移動しますDesign -> Data Model -> Add Model Version
。「古い」モデルの名前が変更され、現在のモデル(緑色のマークが付いているモデル)に変更を加えます。
古いモデルはすべて保持され、アプリケーションに組み込まれるため、アプリは「自動軽量移行」を実行し、既存のデータベースを新しいモデルにアップグレードできます。