swiftrealmrealm-migration

Getting error in realm when i try to add new property in realm object


Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=1 "Provided schema version 0 is less than last set version 1." UserInfo={NSLocalizedDescription=Provided schema version 0 is less than last set version 1., Error Code=1}

Getting this error when I try to add new property in Realm

Not finding any solution for this in swiftui


Solution

  • That's a normal error you will receive during development as you are changing your model and properties around.

    The schema version is set to 1 (or it was set to 1) and then you modified an object so you should set schema version to 2 via a migration.

    From the docs

    Realm Database can automatically migrate added properties, but you must specify an updated schema version when you make these changes.

    If you're just in development, you could also just delete the Realm file and the objects will be built again with schema version 1.

    Please see the documentation for Realm Migrations.

    We've do that a LOT during the early stages of development so we have a button in our UI that just deletes the Realm files - keeping in mind that upon app start, you cannot touch the realm file for this to work. Once you've touched it, it's 'open' and cannot be deleted through code.

    func deleteRealm() {
        do {
            //return the config pointing to where the realm file is located - we
            //  keep ours in the project folder initially
            let config = gGetConfig() 
            let isSuccess = try Realm.deleteFiles(for: config)
            print("deleted realm: \(isSuccess)")
        } catch let err as NSError {
            print(err.localizedDescription)
        }
    }
    

    Edit: Sometimes you can nil the Realm out and then delete it via code but Realm is quite stubborn and sometimes that doesn't work either.