Realm Migration doesn't work

user2179936 picture user2179936 · Jan 4, 2016 · Viewed 12.6k times · Source
    let config = Realm.Configuration(
        // Set the new schema version. This must be greater than the previously used
        // version (if you've never set a schema version before, the version is 0).
        schemaVersion: 1,

        // Set the block which will be called automatically when opening a Realm with
        // a schema version lower than the one set above
        migrationBlock: { migration, oldSchemaVersion in
            // We haven’t migrated anything yet, so oldSchemaVersion == 0
            if (oldSchemaVersion < 1) {
                // Nothing to do!
                // Realm will automatically detect new properties and removed properties
                // And will update the schema on disk automatically
            }
    })

    // Tell Realm to use this new configuration object for the default Realm
    Realm.Configuration.defaultConfiguration = config

    // Now that we've told Realm how to handle the schema change, opening the file
    // will automatically perform the migration
    let realm = try! Realm()

This was put in application(application:didFinishLaunchingWithOptions:)

In my test program, I have changed the fields in my object. I would like to remove everything in the database, and move to the new field types. I've copied the code above from the documentation, but it appears to do nothing. I still get these errors:

fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=0 "Migration is required due to the following errors: 
- Property types for 'unit' property do not match. Old type 'string', new type 'int'
- Property 'reps' has been added to latest object model." UserInfo={NSLocalizedDescription=Migration is required due to the following errors: 
- Property types for 'unit' property do not match. Old type 'string', new type 'int'
- Property 'reps' has been added to latest object model.}: file   /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-700.1.101.15/src/swift/stdlib/public/core/

Any ideas?

Answer

Geoherna picture Geoherna · Aug 11, 2016

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.