CoreData篇(四)-CoreData的简单数据迁移的配置

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_18683985/article/details/87542925

当我们的实体(Entity)新增字段的时候(或者是删减).如果是直接增加不进行配置的话.运行到CoreData代码(例如初始化CoreData时)就会造成崩溃.

那么.如何解决这个问题呢.
首先,我们这次讲解的简单的数据迁移,类似于简单的增减一些字段等操作.

与底层数据库交互的是NSPersistentStoreCoordinator类.我们一般使用下面的方法初始化该类.

- (nullable __kindof NSPersistentStore *)addPersistentStoreWithType:(NSString *)storeType configuration:(nullable NSString *)configuration URL:(nullable NSURL *)storeURL options:(nullable NSDictionary *)options error:(NSError **)error;
storeType: 
// Persistent store types supported by Core Data:
COREDATA_EXTERN NSString * const NSSQLiteStoreType API_AVAILABLE(macosx(10.4),ios(3.0));
COREDATA_EXTERN NSString * const NSXMLStoreType API_AVAILABLE(macosx(10.4)) API_UNAVAILABLE(ios);
COREDATA_EXTERN NSString * const NSBinaryStoreType API_AVAILABLE(macosx(10.4),ios(3.0));
COREDATA_EXTERN NSString * const NSInMemoryStoreType API_AVAILABLE(macosx(10.4),ios(3.0));
这里我一般使用的是NSSQLiteStoreType(底层以SQLite存储)

configuration:
一般都是传nil.

URL:
数据库文件地址,前面一半使用NSSearchPathForDirectoriesInDomains去获取.(因为沙盒前面是动态变化的).
例:
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingString:[NSString stringWithFormat:@"/%@",@"xxx.db"]];
options:
这个"选项"就是做加你单数据迁移需要使用的参数.传入下面这个NSDictionary就行.
NSDictionary *options = @{///简单迁移,复杂迁移需要自行配置迁移文件
                                    NSMigratePersistentStoresAutomaticallyOption: @(YES),
                                    NSInferMappingModelAutomaticallyOption: @(YES),
                                  };

到这里,简单的数据迁移的配置就做好了.

猜你喜欢

转载自blog.csdn.net/qq_18683985/article/details/87542925
今日推荐