Realm Kotlin Update
Modify an Object - Kotlin SDK
realm 내에 저장된 객체 수정
1. realm.write() 또는 realm.writeBlocking()을 사용하여 write 트랜잭션을 엽니다
2. realm.query()를 사용하여 트랜잭션의 mutableRealm을 쿼리합니다. 객체 유형을 query()에 전달된 타입 파라미터로 지정
쿼리가 올바른 개체를 반환하도록 하려면 primary key 값과 같은 고유 식별 정보로 필터링.
3. write 트랜잭션 내에서 개체 속성을 변경합니다. SDK는 realm 대한 변경 사항을 자동으로 유지합니다
realm.write {
// fetch a frog from the realm by primary key
val frog: Frog? =
this.query<Frog>("_id == $0", PRIMARY_KEY_VALUE).first().find()
// modify the frog's age in the write transaction to persist the new age to the realm
frog?.age = 42
}
Upsert an Object - Kotlin SDK
upsert 작업은 개체의 새 인스턴스를 삽입하거나 특정 기준을 충족하는 기존 객체를 업데이트합니다.
1. realm.write() 또는 realm.writeBlocking()으로 쓰기 트랜잭션을 엽니다
2. realm.query()를 사용하여 트랜잭션의 mutableRealm 을 쿼리합니다.객체 유형을 query()에 전달된 타입 파라미터로 지정
upsert 하려는 개체에 대한 고유한 식별 기준으로 기준을 필터링
3.
copyToRealm()을 사용하여 이전 쿼리(존재하는 경우)에서 반환된 개체와 동일한 primary key 를 가진 새 개체를 삽입합니다.
필터와 일치하는 객체가 이미 존재하는 경우 영역은 기존 객체를 업데이트합니다. 필터와 일치하는 개체가 없으면 영역에서 새 객체를 삽입
realm.write {
// fetch a frog from the realm based on some query
val frog: Frog? =
this.query<Frog>("name == 'Wirt'").first().find()
// if the query returned an object, update object from the query
if (frog != null) {
frog.age = 4
frog.species = "Greyfrog"
frog.owner = "L'oric"
} else {
// if the query returned no object, insert a new object with a new primary key.
this.copyToRealm(Frog().apply {
_id = ObjectId.create()
name = "Wirt"
age = 4
species = "Greyfrog"
owner = "L'oric"
})
}
}
Update a Collection - Kotlin SDK
1. realm.query()를 사용하여 개체 컬렉션에 대한 realm을 쿼리합니다.
2. realm.write() 또는 realm.writeBlocking()을 사용하여 write 트랜잭션을 엽니다.
3. 쿼리에서 반환된 RealmResults 집합의 요소를 업데이트합니다.
val tadpoles: RealmQuery<Frog> =
realm.query<Frog>("age > $0", 2)
for (tadpole in tadpoles.find()) {
realm.write {
findLatest(tadpole)?.name = tadpole.name + " Jr."
}
}