一、前言
以前寫過一篇關(guān)于CoreData弯囊,Realm取视,SQLite的文章(文章鏈接),里面大概就是介紹了一下它們的用法和推薦的三方庫常挚,建議再看這篇文章之前可以瀏覽一下之前的那篇文章。今天在這里我就來說一下關(guān)于它們的數(shù)據(jù)庫遷移問題稽物,數(shù)據(jù)庫的遷移都是非嵌套的遷移方式奄毡,這樣就可以避免有的用戶沒有及時(shí)更新帶來的隱患。
二贝或、CoreData
CoreData需要遷移的時(shí)候需要在
- (nullable __kindof NSPersistentStore *)addPersistentStoreWithType:(NSString *)storeType configuration:(nullable NSString *)configuration URL:(nullable NSURL *)storeURL options:(nullable NSDictionary *)options error:(NSError **)error
這個(gè)方法里面的options參數(shù)添加兩個(gè)key-value
NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption:@(YES), NSInferMappingModelAutomaticallyOption:@(YES)};
NSMigratePersistentStoresAutomaticallyOption = YES吼过,那么Core Data會(huì)試著把之前低版本的出現(xiàn)不兼容的持久化存儲(chǔ)區(qū)遷移到新的模型中,這里的例子里咪奖,Core Data就能識(shí)別出是新表
NSInferMappingModelAutomaticallyOption = YES,這個(gè)參數(shù)的意義是Core Data會(huì)根據(jù)自己認(rèn)為最合理的方式去嘗試MappingModel盗忱,從源模型實(shí)體的某個(gè)屬性,映射到目標(biāo)模型實(shí)體的某個(gè)屬性羊赵。
CoreData的遷移方式分為三種:
- 輕量級(jí)的遷移
- 默認(rèn)的遷移方式
- 遷移管理器
2.1.輕量級(jí)遷移方式過程
1.選中.xcdatamodeld文件趟佃,然后選擇Editor-->add Model Version
2.在新的.xcdatamodel中新增一個(gè)字段,author字段
3.然后選擇.xcdatamodeld 選擇Model Version
4.現(xiàn)在我們還需要將原來Book的表結(jié)構(gòu)生成的Book.h昧捷、 Book.m闲昭、Book+CoreDataProperties.h、Book+CoreDataProperties.m替換成新的靡挥,Student同樣序矩。 將原來的這四個(gè)文件直接刪除,然后再創(chuàng)建新的就可以了
xcode8 創(chuàng)建的以后的文件格式會(huì)變成這樣跋破,把原先的Book.h變成了Book+CoreDataClass.h文件簸淀,原先使用的Book.h現(xiàn)在全部改成Book+CoreDataClass.h瓶蝴。
我在原來的基礎(chǔ)上有插入100個(gè)數(shù)據(jù),插入代碼:
NSManagedObjectContext *context = self.appDelegate.managedObjectContext;
NSLog(@"save start");
for (int i = 0; i < 100; i++) {
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];
//創(chuàng)建學(xué)生對(duì)象
Student *stu = [[Student alloc] initWithEntity:entity insertIntoManagedObjectContext:context];
stu.name = [NSString stringWithFormat:@"張三%d", i];
NSEntityDescription *bEntity = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:context];
//創(chuàng)建Book對(duì)象
Book *book = [[Book alloc] initWithEntity:bEntity insertIntoManagedObjectContext:context];
book.title = @"紅樓夢(mèng)";
book.author = @"曹雪芹";
//添加Book對(duì)象
[stu addBooksObject:book];
//保存Student對(duì)象
[_appDelegate saveContext];
}
NSLog(@"save end");
5.前后數(shù)據(jù)庫對(duì)比
2.2默認(rèn)遷移
涉及表映射到另外一張表(實(shí)體)使用默認(rèn)遷移
1.同輕量級(jí)遷移步驟1
2.在新的.xcdatamodel中將Book實(shí)體租幕,修改兩個(gè)屬性名舷手,增刪屬性
3.同輕量級(jí)遷移步驟3
4.同輕量級(jí)遷移步驟4
5.創(chuàng)建MappingModel令蛉,將之前的CoreData.xcdatamodel選作為Source聚霜,后面創(chuàng)建的CoreData2.xcdatamodel作為Target,前后不能選錯(cuò)珠叔。
之后會(huì)生成一個(gè).xcmappingmodel文件:
運(yùn)行新增100個(gè)遷移前后數(shù)據(jù)對(duì)比
2.2遷移管理器遷移
前面的兩種操作都是需要對(duì)表進(jìn)行一次操作才能完成數(shù)據(jù)庫的遷移蝎宇,包括插入數(shù)據(jù),查詢數(shù)據(jù)都可以完成數(shù)據(jù)庫的遷移工作祷安。這里的管理器遷移姥芥,不需要對(duì)表進(jìn)行一次操作。
遷移管理器操作的前5個(gè)步驟和默認(rèn)遷移的步驟一樣汇鞭,只是不需要對(duì)表進(jìn)行一次操作凉唐,我們需要做的是使用遷移器進(jìn)行操作,操作的基本步驟就是先判斷是否需要遷移霍骄,這個(gè)里面有兩部分台囱,一部分是本地是否有這個(gè)數(shù)據(jù)庫,一部分是在有數(shù)據(jù)庫的基礎(chǔ)上判斷存儲(chǔ)數(shù)據(jù)的元數(shù)據(jù)(NSManagedObjectModel)读整,具體操作的代碼如下:
1.是否需要遷移
- (BOOL)judgeDataMigrationIsNeed {
//是否存在文件
NSURL *storeURL = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:@"CoreDataTest.sqlite"];
if (![[NSFileManager defaultManager] fileExistsAtPath:storeURL.path]) {
return NO;
}
NSError *error = nil;
//比較存儲(chǔ)模型的元數(shù)據(jù)簿训。
NSDictionary *sourceMataData = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:NSSQLiteStoreType URL:storeURL error:&error];
NSManagedObjectModel *destinationModel = _appDelegate.managedObjectModel;
if ([destinationModel isConfiguration:nil compatibleWithStoreMetadata:sourceMataData]) {
return NO;
}
return YES;
}
2.遷移器遷移數(shù)據(jù)具體代碼
- (BOOL)executeMigration {
BOOL success = NO;
NSError *error = nil;
NSURL *sourceStore = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:@"CoreDataTest.sqlite"];
//原來的數(shù)據(jù)模型的原信息
NSDictionary *sourceMetadata = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:NSSQLiteStoreType URL:sourceStore error:&error];
//原數(shù)據(jù)模型
NSManagedObjectModel *sourceModel = [NSManagedObjectModel mergedModelFromBundles:nil forStoreMetadata:sourceMetadata];
//最新版數(shù)據(jù)模型
NSManagedObjectModel *destinModel = _appDelegate.managedObjectModel;
//數(shù)據(jù)遷移的映射模型
NSMappingModel *mappingModel = [NSMappingModel mappingModelFromBundles:nil
forSourceModel:sourceModel
destinationModel:destinModel];
if (mappingModel) {
NSError *error = nil;
//遷移管理器
NSMigrationManager *migrationManager = [[NSMigrationManager alloc]initWithSourceModel:sourceModel
destinationModel:destinModel];
//這里可以注冊(cè)監(jiān)聽 NSMigrationManager 的 migrationProgress來查看進(jìn)度
[migrationManager addObserver:self forKeyPath:@"migrationProgress" options:NSKeyValueObservingOptionNew context:nil];
//先把模型存錯(cuò)到Temp.sqlite
NSURL *destinStore = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:@"Temp.sqlite"];
success = [migrationManager migrateStoreFromURL:sourceStore
type:NSSQLiteStoreType
options:nil
withMappingModel:mappingModel
toDestinationURL:destinStore
destinationType:NSSQLiteStoreType
destinationOptions:nil
error:&error];
if (success) {
//替換掉原來的舊的文件
success = [[NSFileManager defaultManager] replaceItemAtURL:sourceStore withItemAtURL:destinStore backupItemName:@"backup.sqlite" options:NSFileManagerItemReplacementUsingNewMetadataOnly | NSFileManagerItemReplacementWithoutDeletingBackupItem resultingItemURL:nil error:nil];
if (success) {
// 這里移除監(jiān)聽就可以了值桩。
[migrationManager removeObserver:self forKeyPath:@"migrationProgress"];
}
}
}
return success;
}
Realm
其實(shí)這里不用說的太啰嗦犯建,遷移的方法github的例子里面有關(guān)于遷移的部分注祖。這里有一點(diǎn)說明一下据块,在沒有完成遷移之前向挖,只要對(duì)realm進(jìn)行訪問都會(huì)崩潰蔬蕊,包括訪問數(shù)據(jù)庫的位置晰筛。我這里就簡(jiǎn)單的做一下演示和說明:
1.我用之前的默認(rèn)的realm創(chuàng)建了一個(gè)default.realm谨究,打開文件逻锐,查看Student
表如下圖:
2.遷移代碼
- 2.1刪除一個(gè)字段
- (void)excuteMigration {
RLMMigrationBlock migratiobBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
// 你修改那個(gè)表就對(duì)那個(gè)進(jìn)行枚舉
if (oldSchemaVersion < 1) {
[migration enumerateObjects:Student.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
// 刪除一個(gè)屬性值 我們不需要任何操作 只需要修改模型即可
}];
}
// 獲取默認(rèn)配置
RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
// 修改默認(rèn)配置版本和遷移block 注意版本號(hào)的變化
config.schemaVersion = 1;
config.migrationBlock = migratiobBlock;
[RLMRealmConfiguration setDefaultConfiguration:config];
// 執(zhí)行打開realm夫晌,完成遷移
[RLMRealm defaultRealm];
}
- 2.1.1 遷移之后
- 2.2增加一個(gè)字段
- (void)excuteMigration {
RLMMigrationBlock migratiobBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
// 你修改那個(gè)表就對(duì)那個(gè)進(jìn)行枚舉
if (oldSchemaVersion < 1) {
[migration enumerateObjects:Student.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
// 刪除一個(gè)屬性值 我們不需要任何操作 只需要修改模型即可
}];
}
// 在前面的基礎(chǔ)上新增一個(gè)字段,如果不需要默認(rèn)值昧诱,可不加這句話慷丽,如果一個(gè)字段需要其他字段的協(xié)助,需要自行進(jìn)行操作
if (oldSchemaVersion < 2) {
[migration enumerateObjects:Student.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
//這里給新增的字段添加一個(gè)默認(rèn)值
newObject[@"sex"] = @"男";
}];
}
// 獲取默認(rèn)配置
RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
// 修改默認(rèn)配置版本和遷移block 注意版本號(hào)的變化
config.schemaVersion = 2;
config.migrationBlock = migratiobBlock;
[RLMRealmConfiguration setDefaultConfiguration:config];
// 執(zhí)行打開realm鳄哭,完成遷移
[RLMRealm defaultRealm];
}
- 2.2.1遷移之后
- 2.3字段類型的變化
- (void)excuteMigration {
RLMMigrationBlock migratiobBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
// 你修改那個(gè)表就對(duì)那個(gè)進(jìn)行枚舉
if (oldSchemaVersion < 1) {
[migration enumerateObjects:Student.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
// 刪除一個(gè)屬性值 我們不需要任何操作 只需要修改模型即可
}];
}
// 在前面的基礎(chǔ)上新增一個(gè)字段要糊,如果不需要默認(rèn)值,可不加這句話,如果一個(gè)字段需要其他字段的協(xié)助锄俄,需要自行進(jìn)行操作
if (oldSchemaVersion < 2) {
[migration enumerateObjects:Student.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
//這里給新增的字段添加一個(gè)默認(rèn)值
newObject[@"sex"] = @"男";
}];
}
if (oldSchemaVersion < 3) {
[migration enumerateObjects:Student.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
if (oldObject && oldObject.objectSchema[@"sex"].type == RLMPropertyTypeString) {
newObject[@"sex"] = @([Student sexTypeForString:oldObject[@"sex"]]);
}
}];
}
};
// 獲取默認(rèn)配置
RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
// 修改默認(rèn)配置版本和遷移block 注意版本號(hào)的變化
config.schemaVersion = 3;
config.migrationBlock = migratiobBlock;
[RLMRealmConfiguration setDefaultConfiguration:config];
// 執(zhí)行打開realm局劲,完成遷移
[RLMRealm defaultRealm];
}
- 2.3.1執(zhí)行之后
*3.Student模型變化
#import <Realm/Realm.h>
#import "Book.h"
// V0
//@interface Student : RLMObject
//@property int num;
//@property NSString *name;
//@property int age;
//@property RLMArray<Book *><Book> *books; //這里表示一對(duì)多的關(guān)系
//
//@end
RLM_ARRAY_TYPE(Student) //宏定義 定義RLMArray<Student>這個(gè)類型
//V1
//@interface Student : RLMObject
//@property int num;
//@property NSString *name;
//@property RLMArray<Book *><Book> *books; //這里表示一對(duì)多的關(guān)系
//
//@end
//V2
//@interface Student : RLMObject
//@property int num;
//@property NSString *name;
//@property NSString *sex;
//@property RLMArray<Book *><Book> *books; //這里表示一對(duì)多的關(guān)系
//@end
//V3
typedef NS_ENUM(NSInteger, Sex) {
Unknow = 0,
Male,
Female
};
@interface Student : RLMObject
@property int num;
@property NSString *name;
@property Sex sex;
@property RLMArray<Book *><Book> *books; //這里表示一對(duì)多的關(guān)系
+ (Sex)sexTypeForString:(NSString *)typeString;
@end
SQLite
關(guān)于SQLite數(shù)據(jù)庫的遷移涉及到iOS的基本全部是FMDB相關(guān)的一個(gè)三方庫FMDBMigrationManager,其實(shí)就是利用SQLite提供的ALTER TABLE命令來進(jìn)行數(shù)據(jù)庫的遷移奶赠,關(guān)于SQLite數(shù)據(jù)庫遷移大家可以自行簡(jiǎn)書相關(guān)FMDB的遷移鱼填,我在這里就不演示了,對(duì)比前面兩種的遷移方式毅戈,我感覺自己以后不會(huì)再用FMDB這個(gè)三方庫了苹丸。
總結(jié)
除非你們的數(shù)據(jù)庫設(shè)計(jì)特別完美,完全能滿足你們以后的版本迭代需求苇经,你不需要進(jìn)行數(shù)據(jù)庫的升級(jí)赘理,但是這種情況也極少數(shù)發(fā)生,所以數(shù)據(jù)庫升級(jí)在所難免扇单,都提前準(zhǔn)備好自己需要使用那種商模,這里為你準(zhǔn)備了一篇關(guān)于數(shù)據(jù)庫遷移的,歡迎收藏蜘澜,歡迎吐槽施流。