Detect if Realm.io db needs migration - if so, destroy it

半世苍凉 提交于 2019-12-18 13:35:38

问题


I'm using Realm for caching over the not-so-long term, and have no need to keep up with schema versions or migrating any time there's a change to a data model.

So, instead of crashing anytime there's a change to the data model, how can my app smartly handle the discrepancy by blowing away the default Realm and starting from scratch?

Thanks in advance!


回答1:


This has been working like a charm for me since Swift 2 introduced try/catch. I just call testRealmFile() from my app delegate at launch, and all is cool after that.

func testRealmFile(){
    do {
        try Realm().objects(Model1)
        try Realm().objects(Model2)
    } catch {
        print("can't access realm, migration needed")
        deleteRealmFile()
    }
}
func deleteRealmFile(){
    if let path = Realm.Configuration.defaultConfiguration.path {
        do{
            try NSFileManager.defaultManager().removeItemAtPath(path)
            print("realm file deleted")
        } catch {
            print("no realm file to delete")
        }
    }
}



回答2:


The Realm Configuration object now has a property called deleteRealmIfMigrationNeeded (also available in Objective C) which if set to true will automatically delete the Realm database file if migration is needed.

Note you may need some other method if you're interested in checking whether or not migration is needed before deleting the database file (e.g. if you want user confirmation before deletion).




回答3:


The simplest way is to check Realm.schemaVersionAtPath(_:) and seeing if that schema version is lower than your current schema version. You can also follow https://github.com/realm/realm-cocoa/issues/1692, which proposes adding a more exact API (one that doesn't require bumping your schema version) allowing you to detect if a migration would be required.



来源:https://stackoverflow.com/questions/30333959/detect-if-realm-io-db-needs-migration-if-so-destroy-it

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