Realm数据库版本迁移
生活随笔
收集整理的這篇文章主要介紹了
Realm数据库版本迁移
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
當你和數據庫打交道的時候,你需要改變數據模型(Model),但是因為Realm中的數據模型被定義為標準的Objective-C interfaces,要改變模型,就像改變其他Objective-C interface一樣輕而易舉。舉個例子,假設有個數據模型Person:
@interface Person : RLMObject @property NSString *firstName; @property NSString *lastName; @property int age; @end 復制代碼當我們想添加一個字段fullName屬性而不是first和last names時,我們可以這樣做:
@interface Person : RLMObject @property NSString *fullName; @property int age; @end 復制代碼接下來執行遷移:
// Inside your [AppDelegate didFinishLaunchingWithOptions:]RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration]; config.schemaVersion = 1; config.migrationBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {//如果從沒遷移過,oldSchemaVersion == 0if (oldSchemaVersion < 1) {// The enumerateObjects:block: method iterates// over every 'Person' object stored in the Realm file[migration enumerateObjects:Person.classNameblock:^(RLMObject *oldObject, RLMObject *newObject) {// 設置新增屬性的值newObject[@"fullName"] = [NSString stringWithFormat:@"%@ %@",oldObject[@"firstName"],oldObject[@"lastName"]];}];} }; [RLMRealmConfiguration setDefaultConfiguration:config]; 復制代碼在遷移的過程中重命名屬性名稱
// Inside your [AppDelegate didFinishLaunchingWithOptions:]RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration]; config.schemaVersion = 1; config.migrationBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {// We haven’t migrated anything yet, so oldSchemaVersion == 0if (oldSchemaVersion < 1) {// The renaming operation should be done outside of calls to `enumerateObjects:`.[migration renamePropertyForClass:Person.className oldName:@"yearsSinceBirth" newName:@"age"];} }; [RLMRealmConfiguration setDefaultConfiguration:config]; 復制代碼官方eg:
RLMRealmConfiguration *config = [RLMRealmConfiguration defaultConfiguration]; config.schemaVersion = 2; config.migrationBlock = ^(RLMMigration *migration, uint64_t oldSchemaVersion) {// enumerateObjects:block: 遍歷了存儲在 Realm 文件中的每一個“Person”對象[migration enumerateObjects:Person.className block:^(RLMObject *oldObject, RLMObject *newObject) {// 只有當 Realm 數據庫的架構版本為 0 的時候,才添加 “fullName” 屬性if (oldSchemaVersion < 1) {newObject[@"fullName"] = [NSString stringWithFormat:@"%@ %@", oldObject[@"firstName"], oldObject[@"lastName"]];}// 只有當 Realm 數據庫的架構版本為 0 或者 1 的時候,才添加“email”屬性if (oldSchemaVersion < 2) {newObject[@"email"] = @"";}// 替換屬性名if (oldSchemaVersion < 3) { // 重命名操作應該在調用 `enumerateObjects:` 之外完成 [migration renamePropertyForClass:Person.className oldName:@"yearsSinceBirth" newName:@"age"]; }}]; }; [RLMRealmConfiguration setDefaultConfiguration:config]; // 現在我們已經成功更新了架構版本并且提供了遷移閉包,打開舊有的 Realm 數據庫會自動執行此數據遷移,然后成功進行訪問 [RLMRealm defaultRealm]; 復制代碼總結
以上是生活随笔為你收集整理的Realm数据库版本迁移的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: css背景图宽度只适应,高度不变
- 下一篇: App Store应用脱壳