.xcdatamodeld の変更による影響を受けないように、persistentStore を再作成 (ドロップ & 作成) したいと思います。
私は AppDelegate で以下のようなコードpersistentStoreCoordinatorを書きました:
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"myproject.sqlite"];
// delete if database exists
NSError *error = nil;
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
// if .xcdatamodeld is changed, fail and in here...
// if not changed, recreate success. all data removed from database
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
NSArray *stores = [_persistentStoreCoordinator persistentStores];
for (NSPersistentStore *store in stores) {
[_persistentStoreCoordinator removePersistentStore:store error:nil];
[[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:nil];
}
// newly create database
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
.xcdatamodeld
(エンティティに新しい列を追加するなど)変更を加えてシミュレーターを再起動すると、最初は失敗しaddPersistentStoreWithType
、ログに次のように表示されます
Unresolved error Error Domain=NSCocoaErrorDomain Code=134100
The operation couldn’t be completed. (Cocoa error 134100.)
どうやってやるの?