8

I updated my data model and wrote the migration in application: didFinishLaunchingWithOptions per Realm documentation:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    let config = Realm.Configuration(

        schemaVersion: 1,


        migrationBlock: { migration, oldSchemaVersion in

            if (oldSchemaVersion < 1) {

            }
    })

           Realm.Configuration.defaultConfiguration = config

        let realm = try! Realm()

My initial VC has a tableView and is embedded in a navigation controller that calls the realm as shown below:

class AllRoundsVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
let realm = try! Realm()

When I leave it like this, my app crashes upon launch stating "fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=0 "Provided schema version 0 is less than last set version 1." UserInfo={NSLocalizedDescription=Provided schema version 0 is less than last set version 1.}

However, when I put a dummy VC infront of the navigation controller with a simple button to segue to the navigation controller everything works fine. I know this has to do with appDidFinishLaunchingWithOptions loading before or after initial VC.

My question is, how can I stop from crashing while still calling try! Realm() on my initial VC? I don't want to keep a pointless VC infront of the tableView just to load the proper schema.

Thanks

JustinM
  • 2,202
  • 2
  • 14
  • 24

2 Answers2

1

after doing some realm research on an unrelated issue I came across a solution to this problem. Here is a link to the solution! link

How can I get the migration to run before the app starts to run the code?

JustinM
  • 2,202
  • 2
  • 14
  • 24
-1

I had the same issue. I got this error: Realm schema version 1 is less than last set version 3 Swift

Here's what needed to be done:

public lazy var realmConfig: Realm.Configuration = {

    var config = Realm.Configuration()

    config.schemaVersion = 3 //the old code is 'config.schemaVersion = 1'

    config.migrationBlock = { newSchemaVersion, oldSchemaVersion in
        if oldSchemaVersion < 3 {}
        if oldSchemaVersion < 2 {}
        if oldSchemaVersion < 1 {}
    }
    return config
}()

when you run the app with config.schemaVersion = 3, the realm cannot be set to lower than 3. So you'd better not use the appbuild(kCFBundleVersionKey) to set the realmConfig.schemaVersion.

Ank
  • 1,704
  • 9
  • 14