Realm Migration doesn't work

和自甴很熟 提交于 2019-11-30 04:01:47

As long as you're in local development only, I'd recommend to reset your Realm database instead of doing a migration. Migrations are the way to go, if you have already shipped a version of your app with another schema and want to keep user data.

You can delete the database by deleting the app from the simulator or the device. Alternatively you can use NSFileManager to delete the Realm file before accessing the database.

let defaultPath = Realm.Configuration.defaultConfiguration.path!
try NSFileManager.defaultManager().removeItemAtPath(defaultPath)

I had a similar issue happening where my app would crash despite the fact that I added the default migration code in didFinishLaunchingWithOptions

The problem was that I was indeed initializing an instance of Realm in my first view controller as a class level property. So removing that class level realm object from my first ViewController fixed the issue.

import UIKit
import RealmSwift

class ViewController: UIViewController{
  let db = try! Realm() // Removing this solved my issue

  func doSomething(){
    let db = try! Realm() // Placed this here instead
  }
}

I instead created the object inside the function that needed it, which is a better approach anyway.

Make sure you don't try to instantiate instance of Realm() before migration config is set in application(application:didFinishLaunchingWithOptions:). When it crashes check execution stack to find which instance raised exception. I had the same error, in my case Realm instance in one of my view controllers were instantiated before migration block was set.

Good luck

I often get the same fatal error too. This usually happens when you make changes to Realm Objects with a "Primary Keys". The quickest and most easy fix is to simply delete the app from the device or simulator - then run your project again.

Are you sure that you updated your schemaVersion properly? If you set schemaVersion: 1 before you made changes, you need to change it to 2 in order for the migration to trigger.

I find best solution:

You need add Realm migration code before didFinishLaunchingWithOptions in willFinishLaunchingWithOptions

func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {

    RealmManager.shared.configureRealm()

    return true
}

Delete app from iPhone and install again. works good.

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