iOS數據庫的遷移(CoreData,Realm,SQLite)

一、前言

以前寫過一篇關于CoreData,Realm,SQLite的文章(文章鏈接),里面大概就是介紹了一下它們的用法和推薦的三方庫,建議再看這篇文章之前可以瀏覽一下之前的那篇文章。今天在這里我就來說一下關于它們的數據庫遷移問題,數據庫的遷移都是非嵌套的遷移方式,這樣就可以避免有的用戶沒有及時更新帶來的隱患。

二、CoreData

CoreData需要遷移的時候需要在
- (nullable __kindof NSPersistentStore *)addPersistentStoreWithType:(NSString *)storeType configuration:(nullable NSString *)configuration URL:(nullable NSURL *)storeURL options:(nullable NSDictionary *)options error:(NSError **)error
這個方法里面的options參數添加兩個key-value
NSDictionary *options = @{NSMigratePersistentStoresAutomaticallyOption:@(YES), NSInferMappingModelAutomaticallyOption:@(YES)};

NSMigratePersistentStoresAutomaticallyOption = YES,那么Core Data會試著把之前低版本的出現不兼容的持久化存儲區遷移到新的模型中,這里的例子里,Core Data就能識別出是新表
NSInferMappingModelAutomaticallyOption = YES,這個參數的意義是Core Data會根據自己認為最合理的方式去嘗試MappingModel,從源模型實體的某個屬性,映射到目標模型實體的某個屬性。

CoreData的遷移方式分為三種:

  • 輕量級的遷移
  • 默認的遷移方式
  • 遷移管理器

    2.1.輕量級遷移方式過程

    1.選中.xcdatamodeld文件,然后選擇Editor-->add Model Version

2.在新的.xcdatamodel中新增一個字段,author字段


3.然后選擇.xcdatamodeld 選擇Model Version


4.現在我們還需要將原來Book的表結構生成的Book.h、 Book.m、Book+CoreDataProperties.h、Book+CoreDataProperties.m替換成新的,Student同樣。 將原來的這四個文件直接刪除,然后再創建新的就可以了

xcode8 以后創建NSManagedObject

xcode8 創建的以后的文件格式會變成這樣,把原先的Book.h變成了Book+CoreDataClass.h文件,原先使用的Book.h現在全部改成Book+CoreDataClass.h。
我在原來的基礎上有插入100個數據,插入代碼:

NSManagedObjectContext *context = self.appDelegate.managedObjectContext;
    NSLog(@"save start");
    for (int i = 0; i < 100; i++) {
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];
        //創建學生對象
        Student *stu = [[Student alloc] initWithEntity:entity insertIntoManagedObjectContext:context];
        stu.name = [NSString stringWithFormat:@"張三%d", i];
        NSEntityDescription *bEntity = [NSEntityDescription entityForName:@"Book" inManagedObjectContext:context];
        //創建Book對象
        Book *book = [[Book alloc] initWithEntity:bEntity insertIntoManagedObjectContext:context];
        book.title = @"紅樓夢";
        book.author = @"曹雪芹";
        //添加Book對象
        [stu addBooksObject:book];
        
        //保存Student對象
        [_appDelegate saveContext];
    }
    NSLog(@"save end");

5.前后數據庫對比

遷移之前
遷移之后

2.2默認遷移

涉及表映射到另外一張表(實體)使用默認遷移
1.同輕量級遷移步驟1
2.在新的.xcdatamodel中將Book實體,修改兩個屬性名,增刪屬性

修改屬性名,新增一個字段并添加默認值

3.同輕量級遷移步驟3
4.同輕量級遷移步驟4
5.創建MappingModel,將之前的CoreData.xcdatamodel選作為Source,后面創建的CoreData2.xcdatamodel作為Target,前后不能選錯。

Source
Target

之后會生成一個.xcmappingmodel文件:

Mapping文件說明

運行新增100個遷移前后數據對比


遷移之前
遷移之后

2.2遷移管理器遷移

前面的兩種操作都是需要對表進行一次操作才能完成數據庫的遷移,包括插入數據,查詢數據都可以完成數據庫的遷移工作。這里的管理器遷移,不需要對表進行一次操作。
遷移管理器操作的前5個步驟和默認遷移的步驟一樣,只是不需要對表進行一次操作,我們需要做的是使用遷移器進行操作,操作的基本步驟就是先判斷是否需要遷移,這個里面有兩部分,一部分是本地是否有這個數據庫,一部分是在有數據庫的基礎上判斷存儲數據的元數據(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;
    
    //比較存儲模型的元數據。
    NSDictionary *sourceMataData = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:NSSQLiteStoreType URL:storeURL error:&error];
    NSManagedObjectModel *destinationModel = _appDelegate.managedObjectModel;
    if ([destinationModel isConfiguration:nil compatibleWithStoreMetadata:sourceMataData]) {
        return NO;
    }
    return YES;
}

2.遷移器遷移數據具體代碼

- (BOOL)executeMigration {
    BOOL success = NO;
    NSError *error = nil;
    
    NSURL *sourceStore = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:@"CoreDataTest.sqlite"];
    
    //原來的數據模型的原信息
    NSDictionary *sourceMetadata = [NSPersistentStoreCoordinator metadataForPersistentStoreOfType:NSSQLiteStoreType URL:sourceStore error:&error];
    //原數據模型
    NSManagedObjectModel *sourceModel = [NSManagedObjectModel mergedModelFromBundles:nil forStoreMetadata:sourceMetadata];
    
    //最新版數據模型
    NSManagedObjectModel *destinModel = _appDelegate.managedObjectModel;
    
    //數據遷移的映射模型
    NSMappingModel *mappingModel = [NSMappingModel mappingModelFromBundles:nil
                                                            forSourceModel:sourceModel
                                                          destinationModel:destinModel];
    if (mappingModel) {
        NSError *error = nil;
        
        //遷移管理器
        NSMigrationManager *migrationManager = [[NSMigrationManager alloc]initWithSourceModel:sourceModel
                                                                             destinationModel:destinModel];
        
        //這里可以注冊監聽  NSMigrationManager 的 migrationProgress來查看進度
        [migrationManager addObserver:self forKeyPath:@"migrationProgress" options:NSKeyValueObservingOptionNew context:nil];
        
        //先把模型存錯到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) {
                //                這里移除監聽就可以了。
                [migrationManager removeObserver:self forKeyPath:@"migrationProgress"];
            }
        }
    }
    return success;
}
遷移之前
遷移之后

Realm

其實這里不用說的太啰嗦,遷移的方法github的例子里面有關于遷移的部分。這里有一點說明一下,在沒有完成遷移之前,只要對realm進行訪問都會崩潰,包括訪問數據庫的位置。我這里就簡單的做一下演示和說明:
1.我用之前的默認的realm創建了一個default.realm,打開文件,查看Student
表如下圖:

遷移之前

2.遷移代碼

  • 2.1刪除一個字段
- (void)excuteMigration {
    RLMMigrationBlock migratiobBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
 //        你修改那個表就對那個進行枚舉
        if (oldSchemaVersion < 1) {
            [migration enumerateObjects:Student.className  block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
//                刪除一個屬性值  我們不需要任何操作 只需要修改模型即可
            }];
            
        }
//    獲取默認配置
    RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
//    修改默認配置版本和遷移block 注意版本號的變化
    config.schemaVersion = 1;
    config.migrationBlock = migratiobBlock;
    [RLMRealmConfiguration setDefaultConfiguration:config];
//    執行打開realm,完成遷移
    [RLMRealm defaultRealm];
}
  • 2.1.1 遷移之后
刪除一個字段之后的表
  • 2.2增加一個字段
- (void)excuteMigration {
    RLMMigrationBlock migratiobBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
//        你修改那個表就對那個進行枚舉
        if (oldSchemaVersion < 1) {
            [migration enumerateObjects:Student.className  block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
//                刪除一個屬性值  我們不需要任何操作 只需要修改模型即可
            }];
            
        }
        
        //              在前面的基礎上新增一個字段,如果不需要默認值,可不加這句話,如果一個字段需要其他字段的協助,需要自行進行操作
        if (oldSchemaVersion < 2) {
            [migration enumerateObjects:Student.className  block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                //這里給新增的字段添加一個默認值
                newObject[@"sex"] = @"男";
            }];
        }
    //    獲取默認配置
    RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
//    修改默認配置版本和遷移block 注意版本號的變化
    config.schemaVersion = 2;
    config.migrationBlock = migratiobBlock;
    [RLMRealmConfiguration setDefaultConfiguration:config];
    //    執行打開realm,完成遷移
    [RLMRealm defaultRealm];
}
  • 2.2.1遷移之后
遷移之后
  • 2.3字段類型的變化
- (void)excuteMigration {
    RLMMigrationBlock migratiobBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {
//        你修改那個表就對那個進行枚舉
        if (oldSchemaVersion < 1) {
            [migration enumerateObjects:Student.className  block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
//                刪除一個屬性值  我們不需要任何操作 只需要修改模型即可
            }];
            
        }
        
        //              在前面的基礎上新增一個字段,如果不需要默認值,可不加這句話,如果一個字段需要其他字段的協助,需要自行進行操作
        if (oldSchemaVersion < 2) {
            [migration enumerateObjects:Student.className  block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
                //這里給新增的字段添加一個默認值
                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"]]);
                }
            }];
        }
    
    };
    //    獲取默認配置
    RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration];
    //    修改默認配置版本和遷移block 注意版本號的變化
    config.schemaVersion = 3;
    config.migrationBlock = migratiobBlock;
    [RLMRealmConfiguration setDefaultConfiguration:config];
    //    執行打開realm,完成遷移
    [RLMRealm defaultRealm];
}
  • 2.3.1執行之后
遷移之后

*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;  //這里表示一對多的關系
//
//@end
RLM_ARRAY_TYPE(Student)  //宏定義  定義RLMArray<Student>這個類型

//V1
//@interface Student : RLMObject
//@property int num;
//@property NSString *name;
//@property RLMArray<Book *><Book> *books;  //這里表示一對多的關系
//
//@end

//V2
//@interface Student : RLMObject
//@property int num;
//@property NSString *name;
//@property NSString *sex;
//@property RLMArray<Book *><Book> *books;  //這里表示一對多的關系

//@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;  //這里表示一對多的關系

+ (Sex)sexTypeForString:(NSString *)typeString;
@end

SQLite

關于SQLite數據庫的遷移涉及到iOS的基本全部是FMDB相關的一個三方庫FMDBMigrationManager,其實就是利用SQLite提供的ALTER TABLE命令來進行數據庫的遷移,關于SQLite數據庫遷移大家可以自行簡書相關FMDB的遷移,我在這里就不演示了,對比前面兩種的遷移方式,我感覺自己以后不會再用FMDB這個三方庫了。

總結

除非你們的數據庫設計特別完美,完全能滿足你們以后的版本迭代需求,你不需要進行數據庫的升級,但是這種情況也極少數發生,所以數據庫升級在所難免,都提前準備好自己需要使用那種,這里為你準備了一篇關于數據庫遷移的,歡迎收藏,歡迎吐槽。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,406評論 6 538
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,034評論 3 423
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,413評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,449評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,165評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,559評論 1 325
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,606評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,781評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,327評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,084評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,278評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,849評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,495評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,927評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,172評論 1 291
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,010評論 3 396
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,241評論 2 375

推薦閱讀更多精彩內容