Realm オブジェクトの削除
Realm オブジェクトの削除は、書込みトランザクション (write transaction) 内で実行される必要があります。 書込みトランザクション (write transaction) の詳細については、「トランザクション 」を参照してください。
Realm ファイル自体を削除する場合は、「 Realm の削除 」を参照してください。
重要
削除後のオブジェクトを使用しない
Realm から削除したオブジェクトにアクセスしたり、そのオブジェクトを変更したりすることはできません。 削除されたオブジェクトを使用しようとすると、Realm はエラーをスローします。
このページの例について
このページの例では、次のモデルを使用します。
// DogToy.h @interface DogToy : RLMObject @property NSString *name; @end // Dog.h @interface Dog : RLMObject @property NSString *name; @property int age; @property NSString *color; // To-one relationship @property DogToy *favoriteToy; @end // Enable Dog for use in RLMArray RLM_COLLECTION_TYPE(Dog) // Person.h // A person has a primary key ID, a collection of dogs, and can be a member of multiple clubs. @interface Person : RLMObject @property int _id; @property NSString *name; // To-many relationship - a person can have many dogs @property RLMArray<Dog *><Dog> *dogs; // Inverse relationship - a person can be a member of many clubs @property (readonly) RLMLinkingObjects *clubs; @end RLM_COLLECTION_TYPE(Person) // DogClub.h @interface DogClub : RLMObject @property NSString *name; @property RLMArray<Person *><Person> *members; @end // Dog.m @implementation Dog @end // DogToy.m @implementation DogToy @end // Person.m @implementation Person // Define the primary key for the class + (NSString *)primaryKey {     return @"_id"; } // Define the inverse relationship to dog clubs + (NSDictionary *)linkingObjectsProperties {     return @{         @"clubs": [RLMPropertyDescriptor descriptorWithClass:DogClub.class propertyName:@"members"],     }; } @end // DogClub.m @implementation DogClub @end 
class Dog: Object {      var name = ""      var age = 0      var color = ""      var currentCity = ""      var citiesVisited: MutableSet<String>      var companion: AnyRealmValue     // Map of city name -> favorite park in that city      var favoriteParksByCity: Map<String, String> } 
オブジェクトの削除
Realm からオブジェクトを削除するには、書込みトランザクション内で -[RMRealm deleteObject:]にオブジェクトを渡します。
[realm transactionWithBlock:^() {     // Delete the instance from the realm.     [realm deleteObject:dog]; }]; 
Realm からオブジェクトを削除するには、書込みトランザクション内でオブジェクトをRealm.delete(_:)に渡します。
// Previously, we've added a dog object to the realm. let dog = Dog(value: ["name": "Max", "age": 5]) let realm = try! Realm() try! realm.write {     realm.add(dog) } // Delete the instance from the realm. try! realm.write {     realm.delete(dog) } 
複数のオブジェクトの削除
バージョン 10.19.0 の新機能。
Realm からオブジェクトのコレクションを削除するには、書込みトランザクション内でコレクションをRealm.delete(_:)に渡します。
let realm = try! Realm() try! realm.write {     // Find dogs younger than 2 years old.     let puppies = realm.objects(Dog.self).where {         $0.age < 2     }     // Delete the objects in the collection from the realm.     realm.delete(puppies) } 
Realm からオブジェクトのコレクションを削除するには、書込みトランザクション内でコレクションをRealm.delete(_:)に渡します。
let realm = try! Realm() try! realm.write {     // Find dogs younger than 2 years old.     let puppies = realm.objects(Dog.self).filter("age < 2")     // Delete the objects in the collection from the realm.     realm.delete(puppies) } 
Realm からオブジェクトのコレクションを削除するには、書込みトランザクション内でコレクションを-[Realm deleteObjects:]に渡します。
RLMRealm *realm = [RLMRealm defaultRealm]; [realm transactionWithBlock:^() {     // Find dogs younger than 2 years old.     RLMResults<Dog *> *puppies = [Dog objectsInRealm:realm where:@"age < 2"];     // Delete all objects in the collection from the realm.     [realm deleteObjects:puppies]; }]; 
オブジェクトとその関連オブジェクトの削除
親オブジェクトを削除する際に、関連するオブジェクトも削除したい場合があります。 これを連鎖削除と呼びます。 Realm は関連オブジェクトを削除しません。 オブジェクトを自分で削除しない場合、Realm 内で孤立したままになります。 これが問題になるかどうかは、アプリケーションのニーズによって異なります。
依存関係オブジェクトを削除する最良の方法は、親オブジェクトを削除する前に、依存関係を反復処理して削除することです。
[realm transactionWithBlock:^() {     // Delete Ali's dogs.     [realm deleteObjects:[ali dogs]];     // Delete Ali.     [realm deleteObject:ali]; }]; 
let person = realm.object(ofType: Person.self, forPrimaryKey: 1)! try! realm.write {     // Delete the related collection     realm.delete(person.dogs)     realm.delete(person) } 
特定のタイプのすべてのオブジェクトの削除
特定のオブジェクトタイプのすべてのオブジェクトを Realm から削除するには、書込みトランザクション内で+[ YourRealmObjectClass allObjectsInRealm:]の結果を-[Realm deleteObjects:]に渡します。  YourRealmObjectClassを Realm オブジェクト クラス名に置き換えます。
RLMRealm *realm = [RLMRealm defaultRealm]; [realm transactionWithBlock:^() {     // Delete all instances of Dog from the realm.     RLMResults<Dog *> *allDogs = [Dog allObjectsInRealm:realm];     [realm deleteObjects:allDogs]; }]; 
特定のオブジェクトタイプのすべてのオブジェクトを Realm から削除するには、書込みトランザクション内で削除するタイプの Realm.objects(_:) の結果を Realm.delete(_:) に渡します。
let realm = try! Realm() try! realm.write {     // Delete all instances of Dog from the realm.     let allDogs = realm.objects(Dog.self)     realm.delete(allDogs) } 
Realm 内のすべてのオブジェクトの削除
Realm からすべてのオブジェクトを削除するには、書込みトランザクション内で-[RMRealm deleteAllObjects]を呼び出します。 これにより、すべてのオブジェクト インスタンスの Realm はクリアされますが、Realm のスキーマには影響しません。
RLMRealm *realm = [RLMRealm defaultRealm]; [realm transactionWithBlock:^() {     // Delete all objects from the realm.     [realm deleteAllObjects]; }]; 
Realm からすべてのオブジェクトを削除するには、 Realm.deleteAll()を呼び出します 書込みトランザクション (write transaction) 内。 これにより、すべてのオブジェクト インスタンスの Realm はクリアされますが、Realm のスキーマには影響しません。
let realm = try! Realm() try! realm.write {     // Delete all objects from the realm.     realm.deleteAll() } 
マップのキーと値の削除
マップエントリは、次の方法で削除できます。
キーと値を削除するには、
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から特定の要素を削除したり、セットからすべての要素をクリアしたりできます。 複数のセットを操作している場合は、一方のセットの要素を他方のセットから排除することもできます。 「 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 の値の削除
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 } 
オブジェクトの非同期な削除
Swift の同時実行機能を使用すると、アクター分離された Realm によりオブジェクトを非同期に削除できます。
RealmActor Use Realm with Atlas で定義された例の] 関数は、アクター分離された 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 への書き込みを実行する方法の詳細については、 「 アクターで Realm を使用する - Swift SDK 」を参照してください。