我希望重新创建(删除并创建)persistentStore,以防受到.xcdatamodeld的更改的影响。
我在AppDelegate中编写了以下代码持久存储协调器:
- (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.)
我该如何做到这一点?