问题
On my first app I used within my persistant store coordinater a NSXMLStoreType.
[storeCooordinator addPersistentStoreWithType:NSXMLStoreType configuration:nil URL:storeURL options:options error:nil];
Now, I like to change to a NSSQLiteStoreType:
[storeCooordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:nil];
The app crashes, if I simply change the store type. So what I have to do? May I have to do once:
- check if the old store exists and
- if yes convert it to sqlite and
- delete afterwards the old xml store?
I have no idea how to convert it to sqlite. The models are the same.
EDIT & ANSWER
I use this solution to migrate once the database (thanks to 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];
}
}
回答1:
You can use migratePersistentStore:toURL:options:withType:error:
as described in Apples Core Data documentation.
If this should happen automatically, you will need to add the migration at startup.
来源:https://stackoverflow.com/questions/21566819/xcode-core-data-change-existing-xml-to-sqlite-nsxmlstoretype-to-nssqlitestoret