Xcode Core Data: Change existing XML to Sqlite (NSXMLStoreType to NSSQLiteStoreType)

独自空忆成欢 提交于 2019-12-22 13:03:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!