这是- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
替换代码,如果你设置在XCode的新项目时打勾的核心数据框,你得到的。
它试图打开现有源码文件(如果必要的话使用轻量级迁移)。如果失败,它将删除并重新创建商店。
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil) {
return _persistentStoreCoordinator;
}
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
NSError *error = nil;
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:self.storeURL options:options error:&error])
{
NSLog(@"Couldn't open the store. error %@, %@", error, [error userInfo]);
[self deleteSqliteFilesForStore:self.storeURL];
if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:self.storeURL options:options error:&error])
{
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
// or [NSException raise ...]
}
else
{
NSLog(@"Store deleted and recreated");
// TEST DATA RE-INITIALIZATION CODE GOES HERE
}
}
else
{
NSLog(@"Existing Store opened successfully");
}
return _persistentStoreCoordinator;
}
- (void)deleteSqliteFilesForStore:(NSURL *)storeURL
{
NSURL *baseURL = [storeURL URLByDeletingPathExtension];
// Delete the associated files as well as the sqlite file
for (NSString *pathExtension in @[@"sqlite",@"sqlite-shm",@"sqlite-wal"])
{
NSURL *componentURL = [baseURL URLByAppendingPathExtension:pathExtension];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[componentURL path]];
if(fileExists)
{
[[NSFileManager defaultManager] removeItemAtPath:[componentURL path] error:nil];
}
}
}
也许[核心数据模型版本控制和数据迁移(http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/CoreDataVersioning/Articles/Introduction.html)指南帮助。 – Rob
是的,我正在挖掘它。 isConfiguration:compatibleWithStoreMetadata:为我解决了这个问题,但我需要一个实现的例子来明确它是如何使用的。 –
'isConfiguration:compatibleWithStoreMetadata:'不会告诉你,有一个新的版本 - 它只会告诉你,有一个_incompatible_版本。如果你的新版本可以自动迁移,那么这将返回'是'。 _I'm只有90%肯定这一点 - 你可能不得不尝试着去证明我是对/错_ – deanWombourne