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

I use Realm for short-term caching and don’t need to keep up with the versions of the schema or transfer any time to change the data model.

So, instead of failing at any time to happen with a change in the data model, how does my application skillfully deal with this discrepancy by blowing off the default Realm and starting from scratch?

Thanks in advance!

+4
source share
3 answers

This works like a charm for me since Swift 2 introduced try / catch. I just call the testRealmFile()application from my delegate at startup, and after that, everything is cool.

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")
        }
    }
}
+3
source

Realm deleteRealmIfMigrationNeeded ( Objective C), , true, Realm, .

, - , (, , ).

+1

- Realm.schemaVersionAtPath(_:) , , . https://github.com/realm/realm-cocoa/issues/1692, API (, ), .

0

All Articles