在我的第一个应用程序中,我在持久存储协调器中使用了 NSXM StoreType。
[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。模型是相同的。
编辑并回答
我使用这个解决方案来迁移一次数据库(感谢沃尔克)
//-> 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];
}
}
您可以使用migratePersistentStore:toURL:options:withType:error:
如中所述苹果核心数据文档 https://developer.apple.com/library/ios/documentation/cocoa/conceptual/CoreData/Articles/cdUsingPersistentStores.html.
如果这种情况自动发生,您将需要在启动时添加迁移。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)