How can I avoid migration in RealmSwift

那年仲夏 提交于 2019-12-04 18:07:55

问题


I am just testing some configurations with Realm and therefore I have added and deleted variables and lists from my realm classes. Since I am just testing I do not want to go through the migration process - I also don't have any data which is effected for continuity.

Is there any way to get around migration being requested automatically by Realm?


回答1:


There are two ways to skip migration error regardless schema changes.

  1. Use deleteRealmIfMigrationNeeded property. If it is true, recreate the Realm file with the provided schema if a migration is required.

    let config = Realm.Configuration(deleteRealmIfMigrationNeeded: true)
    Realm.Configuration.defaultConfiguration = config
    
    let realm = try! Realm()
    ...
    

      

  2. Increment schema version every launch. Realm has auto migration feature. If you don't need to migrate existing data, you can just increment schema version. Schema will be changed by Realm automatically.

    let config = Realm.Configuration(schemaVersion: try! schemaVersionAtURL(Realm.Configuration.defaultConfiguration.fileURL!) + 1)
    Realm.Configuration.defaultConfiguration = config
    
    let realm = try! Realm()
    ...
    



回答2:


In Swift 3

Migration in Realm can be easily avoid by placing this code inside "didFinishLaunchingWithOptions" method in AppDelegate class.

var config = Realm.Configuration()
config.deleteRealmIfMigrationNeeded = true
Realm.Configuration.defaultConfiguration = config

This will delete the realm database if migration is required with new setup.




回答3:


Swift 4

var config = Realm.Configuration()
config.deleteRealmIfMigrationNeeded = true
Realm.Configuration.defaultConfiguration = config


来源:https://stackoverflow.com/questions/38193265/how-can-i-avoid-migration-in-realmswift

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