Realm migrations in Swift

前端 未结 2 749
鱼传尺愫
鱼传尺愫 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:07

    Because you just create Realm.Configuration. Migration block is invoked by Realm if needed. You cannot invoke migration directly.

    So to be invoke migration block, you should set configuration object to Realm, or set as default configuration. Then create Realm instance.

    So You need to do the following:

    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
            switch oldSchemaVersion {
            case 1:
                break
            default:
                // Nothing to do!
                // Realm will automatically detect new properties and removed properties
                // And will update the schema on disk automatically
                self.zeroToOne(migration)
            }
    })
    
    let realm = try! Realm(configuration: config) // Invoke migration block if needed
    

提交回复
热议问题