Realm 특정 클래스명 변경(A -> B) 해보기
1. 프로젝트 코드 내 클래스 삭제
2. Realm DB 내 클래스 및 데이터 삭제
(기존 앱 사용자가 있으므로 Realm Migration이 되어야 함)
migration 로직 내 delete, deleteData를 이용해보려 하였으나 에러 발생
Can only delete an object from the Realm it belongs to
migration.delete(newObject)
migration.deleteData(forType: newObject)
대응 방안
- 신규 클래스 생성 후 데이터를 기존 클래스에서 가져와서 세팅함
- 기존 클래스 내 Realm 데이터 삭제 (단, 코드 내 기존 클래스 유지 되어야 함)
// 신규 클래스를 생성하고, 데이터를 기존 클래스에서 가져와서 설정한다.
migration.enumerateObjects(ofType: B.className()) { oldObject, newObject in
if let oldItems = oldObject?["AItems"] as? List<MigrationObject>,
let newItems = newObject!["BItems"] as? List<MigrationObject> {
for oldItem in oldItems {
let newItem = migration.create(B.className())
newItem["code"] = oldItem["code"]
newItem["name"] = oldItem["name"]
newItems.append(newItem)
}
}
}
// 기존 A 클래스 내 데이터 삭제
// 클래스 자체는 Realm에서 삭제가 안됨
migration.enumerateObjects(ofType: "A") { _, newObject in
guard let newObject = newObject else { return }
migration.delete(newObject)
}
기존 클래스를 코드와 DB 데이터 모두 삭제하고 신규 클래스로 적용하는 깔끔한 방법은 아직 찾지 못했다.