在我的第一个应用程序中,我在持久存储协调器中使用了 NSXMLStoreType。
[storeCooordinator addPersistentStoreWithType:NSXMLStoreType configuration:nil URL:storeURL options:options error:nil];
现在,我想更改为 NSSQLiteStoreType:
[storeCooordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:nil];
如果我只是更改商店类型,应用程序就会崩溃。那么我必须做什么呢?我可以做一次吗:
- 检查旧商店是否存在并且
- 如果是,将其转换为 sqlite 并
- 之后删除旧的 xml 存储吗?
我不知道如何将其转换为sqlite。型号是一样的。
EDIT & ANSWER
我使用此解决方案迁移一次数据库(感谢 Volker)
//-> applicationFilesDirectory is the url to the documents directory
NSURL* oldURL = [applicationFilesDirectory URLByAppendingPathComponent:@"DBName1.xml"];
NSURL* newURL = [applicationFilesDirectory URLByAppendingPathComponent:@"DBName2.sqlite"];
NSError *error = nil;
NSFileManager * fileManager = [NSFileManager defaultManager];
//-> if file exists
if ([fileManager fileExistsAtPath:[oldURL path]]) {
NSLog(@"File is here");
NSManagedObjectModel* managedModel = [NSManagedObjectModel mergedModelFromBundles:nil];
NSPersistentStoreCoordinator* tempCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedModel];
id xmlStore = [tempCoordinator addPersistentStoreWithType:NSXMLStoreType configuration:nil URL:oldURL options:options error:nil];
[tempCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:newURL options:options error:nil];
if ( ![tempCoordinator migratePersistentStore:xmlStore toURL:newURL options:options withType:NSSQLiteStoreType error:&error] ) {
//-> delete the old file from directory
[fileManager removeItemAtURL:oldURL error:NULL];
}
}
最佳答案
您可以按照 Apples Core Data documentation 中所述使用 migratePersistentStore:toURL:options:withType:error:
.
如果这应该自动发生,您将需要在启动时添加迁移。
关于ios - Xcode核心数据: Change existing XML to Sqlite (NSXMLStoreType to NSSQLiteStoreType),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21566819/