iOS application coreData with PersistentStore as static sqlite Data Migration?

Deadly 提交于 2019-12-13 06:05:07

问题


The app is using a static sqlite(initial data) from bundle directory as a persistent store for Coredata. The sqlite has 7 tables of which one table is modified by adding an extra column/field. How does I make coreData understand that the persistent store(store) is changed and it needs to take the new update ? Is there any Model version concept for sqlite like we do for coredata ?


回答1:


For those who doesn't want to dig into documentation and is searching for a quick fix:

1>Open your .xcdatamodeld file

2> click on Editor

3> select Add model version...

4> Add a new version of your model (the new group of datamodels added)

5> select the main file, open file inspector (right-hand panel)

6> and under Versioned core data model select your new version of data model for current data model

7> THAT'S NOT ALL ) You should perform so called "light migration".

8> Go to your AppDelegate and find where the persistentStoreCoordinator is being created

9> Find this line if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])

10> Replace nil options with @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES} (actually provided in the commented code in that method)

Here you go, have fun! P.S. This only applies for lightweight migration. For your migration to qualify as a lightweight migration, your changes must be confined to this narrow band:

Add or remove a property (attribute or relationship).

Make a nonoptional property optional.

Make an optional attribute nonoptional, as long as you provide a default value.

Add or remove an entity.

Rename a property.

Rename an entity.




回答2:


If you are just adding attributes to an entity, you can use the coredata lightweight migration suggest on Apple documentation

NSError *error = nil;
NSURL *storeURL = <#The URL of a persistent store#>;
NSPersistentStoreCoordinator *psc = <#The coordinator#>;
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
    [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
    [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

BOOL success = [psc addPersistentStoreWithType:<#Store type#>
                    configuration:<#Configuration or nil#> URL:storeURL
                    options:options error:&error];
if (!success) {
    // Handle the error.
}


来源:https://stackoverflow.com/questions/29918219/ios-application-coredata-with-persistentstore-as-static-sqlite-data-migration

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