문서 메뉴

문서 홈애플리케이션 개발Atlas Device SDK

CRUD - 삭제 - Swift SDK

이 페이지의 내용

  • Realm 객체 삭제
  • 이 페이지의 예시 관련 정보
  • 객체 삭제
  • 여러 객체 삭제
  • 객체 및 관련 객체 삭제
  • 특정 타입의 모든 객체 삭제
  • Realm의 모든 객체 삭제
  • 맵 키/값 삭제
  • MutableSet 요소 삭제
  • AnyRealmValue 값 삭제하기
  • 비동기적으로 객체 삭제

Realm 객체 삭제는 쓰기 트랜잭션(write transaction) 내에서 이루어져야 합니다. 쓰기 트랜잭션에 대한 자세한 내용은 트랜잭션을 참조하세요.

Realm 파일 자체를 삭제하려면 Realm 삭제하기를 참조하세요.

중요

삭제 후 객체를 사용하지 않아야 합니다.

Realm에서 객체를 삭제한 후에는 해당 객체에 액세스하거나 수정할 수 없습니다. 삭제된 객체를 사용하려고 하면 Realm은 오류를 발생시킵니다.

이 페이지의 예시에서는 다음 모델을 사용합니다.

상위 객체를 삭제할 때 관련 객체도 함께 삭제하고 싶을 수 있습니다. 이것을 체인 삭제라고 합니다. Realm은 사용자를 대신해 관련 객체를 삭제하지 않습니다. 객체를 직접 삭제하지 않으면 해당 객체는 사용자의 Realm 안에서 고아로 남게 됩니다. 이것이 문제가 되는지 여부는 애플리케이션의 요구 사항에 따라 다릅니다.

종속 객체를 삭제하는 가장 좋은 방법은 상위 객체를 삭제하기 전에 종속 객체를 순회(iterate)하여 삭제하는 것입니다.

다음과 같은 몇 가지 방법으로 항목을 삭제할 수 있습니다.

  • removeObject(for:)을(를) 사용하여 키와 값을 제거합니다.

  • 딕셔너리 값이 선택 사항인 경우 키 값을 nil로 설정하여 키를 유지할 수 있습니다.

let realm = try! Realm()
// Find the dog we want to update
let wolfie = realm.objects(Dog.self).where {
$0.name == "Wolfie"
}.first!
// Delete an entry
try! realm.write {
// Use removeObject(for:)
wolfie.favoriteParksByCity.removeObject(for: "New York")
// Or assign `nil` to delete non-optional values.
// If the value type were optional (e.g. Map<String, String?>)
// this would assign `nil` to that entry rather than deleting it.
wolfie.favoriteParksByCity["New York"] = nil
}
XCTAssertNil(wolfie.favoriteParksByCity["New York"])

MutableSet 에서 특정 요소를 삭제하거나 세트에서 모든 요소를 지울 수 있습니다. 여러 세트로 작업하는 경우 다른 세트에서 한 세트의 요소를 제거할 수도 있습니다. 참조: MutableSet 속성 업데이트.

let realm = try! Realm()
// Record a dog's name and list of cities he has visited.
let dog = Dog()
dog.name = "Maui"
let dogCitiesVisited = ["New York", "Boston", "Toronto"]
try! realm.write {
realm.add(dog)
dog.citiesVisited.insert(objectsIn: dogCitiesVisited)
}
XCTAssertEqual(dog.citiesVisited.count, 3)
// Later... we decide the dog didn't really visit Toronto
// since the plane just stopped there for a layover.
// Remove the element from the set.
try! realm.write {
dog.citiesVisited.remove("Toronto")
}
XCTAssertEqual(dog.citiesVisited.count, 2)
// Or, in the case where the person entered the data for
// the wrong dog, remove all elements from the set.
try! realm.write {
dog.citiesVisited.removeAll()
}
XCTAssertEqual(dog.citiesVisited.count, 0)

AnyRealmValue 값을 삭제하려면 .none으로 설정합니다.

let realm = try! Realm()
// Wolfie's companion is "Fluffy the Cat", represented by a string.
// Fluffy has gone to visit friends for the summer, so Wolfie has no companion.
let wolfie = realm.objects(Dog.self).where {
$0.name == "Wolfie"
}.first!
try! realm.write {
// You cannot set an AnyRealmValue to nil; you must set it to `.none`, instead.
wolfie.companion = .none
}

Actor-isolated Realm을 사용하여 객체를 비동기적으로 삭제하기 위해 Swift 동시성 기능을 사용할 수 있습니다.

Actors와 함께 Realm 사용하기 페이지에 정의RealmActor 예시의 함수는 Actor-isolated Realm에서 객체를 삭제하는 방법을 보여줍니다.

func deleteTodo(id: ObjectId) async throws {
try await realm.asyncWrite {
let todoToDelete = realm.object(ofType: Todo.self, forPrimaryKey: id)
realm.delete(todoToDelete!)
}
}

그리고 Swift의 비동기 구문을 사용하여 이 삭제를 수행할 수도 있습니다.

let actor = try await RealmActor()
let todoId = await actor.getObjectId(forTodoNamed: "Keep Mr. Frodo safe from that Gollum")
try await actor.deleteTodo(id: todoId)
let updatedTodoCount = await actor.count
if updatedTodoCount == todoCount - 1 {
print("Successfully deleted the todo")
}

이 작업은 호출 스레드에서 I/O를 차단하거나 수행하지 않습니다. Swift 동시성 기능을 사용하여 Realm에 쓰는 방법에 대해 자세히 알아보려면 Actors와 함께 Realm 사용 - Swift SDK를 참조하세요.

← CRUD - 업데이트 - Swift SDK