👨🏻‍💻iOS 공부/ErrorHandling

[Realm] Migration Error

728x90
반응형

원인 :  기존 데이터 모델에서 속성을 변경할 경우 발생하는 에러 

 

아래 케이스로 원인을 조금 더 자세하게 살펴보자.

 

// 기존
class Person: Object {
    @objc dynamic var firstName = ""
    @objc dynamic var lastName = ""
    @objc dynamic var age = 0
}

 

위 모델에서 아래의 모델처럼 조금이라도 구조를 변경하게 되면 오류를 발생시킨다.

 

class Person: Object {
    @objc dynamic var firstName = ""
    @objc dynamic var lastName = ""
}

 

이 때 공식 홈페이지의 가이드라인을 따라 아래 코드를 AppDelegate의 didFinishLaunchingWithOptions에 넣어주면 해결된다. 

아래 코드를 넣지 않고 해결하려면... 매번 앱을 지웠다가 빌드할 때 다시 깔아줘야 정상적으로 작동한다!

 

모델을 얼마 안바꾸겠지... 싶어서 그대로 두고 지우고 깔고 반복하다가.. 모델을 변경하는 빈도도 높아지고 추후 배포 이후에 모델이 변경될 때 마다 사용자 단에서 에러를 발생 시킬 수 있겠다고 생각되어 대응하기로 했다. 

 

// Inside your application(application:didFinishLaunchingWithOptions:)

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()

++++

이대로 한 번 실행 후 또 모델을 바꾸고 실행하면 제대로 빌드되지 않는다. 왜냐 SchemaVersion을 바꿔주지 않았기 때문이다. 

즉 모델을 변경하고 빌드할 때 마다 AppDelegate의 SchemaVersion를 올려주면 해결된다. 

 

SchemaVersion: 2

https://docs.mongodb.com/realm-legacy/docs/swift/latest/#migrations

 

Realm: Create reactive mobile apps in a fraction of the time

Oops something went wrong You will not be receiving an email shortly with details

docs.mongodb.com

 

728x90
반응형