Detect if Realm.io db needs migration - if so, des

2019-02-07 09:18发布

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!

3条回答
别忘想泡老子
2楼-- · 2019-02-07 09:56

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楼-- · 2019-02-07 10:08

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")
        }
    }
}
查看更多
唯我独甜
4楼-- · 2019-02-07 10:09

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.

查看更多
登录 后发表回答