Realm migrations in Swift

前端 未结 2 771
鱼传尺愫
鱼传尺愫 2021-02-05 16:13

I have a Realm Object modeled as so

class WorkoutSet: Object {
     // Schema 0
     dynamic var exerciseName: String = \"\"
     dynamic var reps: Int = 0
              


        
2条回答
  •  遇见更好的自我
    2021-02-05 17:02

    You will need to invoke the migration. Merely creating a configuration, won't invoke it. There are two ways of doing this:

    1. Set your configuration with migration as Realm's default configuration-

      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
      
          if oldSchemaVersion < 1 {
            migration.enumerate(WorkoutSet.className()) { oldObject, newObject in
              newObject?["setCount"] = setCount
            }    
          }
        }
      ) 
      Realm.Configuration.defaultConfiguration = config   
      

    OR

    1. Migrate manually using migrateRealm :

    migrateRealm(config)

    Now your migration should work properly.

提交回复
热议问题