我想重新创建(删除并创建)persistentStore,使其不受更改 .xcdatamodeld 的影响。
我在 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.)
我该怎么做?
最佳答案
下面的代码对我来说似乎工作得很好。
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"myproject.sqlite"];
// delete database if exists
[[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:nil];
// create database
NSError *error = nil;
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return _persistentStoreCoordinator;
}
我在下面检查(在设备和模拟器中):
- 首次启动时,应创建数据库
- 编辑 .xcdatamodeld(添加/编辑/删除列或实体)然后重新启动,应重新创建数据库
感谢您的建议。
关于ios - 如何重新创建 persistentStore 不受更改 .xcdatamodeld 的影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20324174/