Delete Realm Objects
La eliminación de objetos de dominio debe realizarse dentro de las transacciones de escritura. Para más información sobre las transacciones de escritura, consulte: Transacciones.
If you want to delete the Realm file itself, see: Delete a Realm.
Importante
No utilices objetos después de borrar
You cannot access or modify an object after you have deleted it from a realm. If you try to use a deleted object, Realm throws an error.
Acerca de los ejemplos en esta página
Los ejemplos en esta página utilizan los siguientes modelos:
// 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> }
Eliminar un objeto
Para eliminar un objeto de un reino, pase el objeto a -[RLMRealm deleteObject:] dentro de una transacción de escritura.
[realm transactionWithBlock:^() { // Delete the instance from the realm. [realm deleteObject:dog]; }];
Para eliminar un objeto de un reino, pase el objeto a Realm.delete(_:) dentro de una transacción de escritura.
// 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) }
Delete Multiple Objects
Nueva en la versión 10.19.0.
Para eliminar una colección de objetos de un reino, pase la colección a Realm.delete(_:) dentro de una transacción de escritura.
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) }
Para eliminar una colección de objetos de un reino, pase la colección a Realm.delete(_:) dentro de una transacción de escritura.
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) }
To delete a collection of objects from a realm, pass the collection to -[Realm deleteObjects:] inside of a write transaction.
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]; }];
Eliminar un objeto y sus objetos relacionados
A veces, es necesario eliminar objetos relacionados al eliminar el objeto principal. Esto se denomina eliminación encadenada. Realm no elimina automáticamente los objetos relacionados. Si no los elimina usted mismo, permanecerán huérfanos en su dominio. Que esto sea un problema depende de las necesidades de su aplicación.
The best way to delete dependent objects is to iterate through the dependencies and delete them before deleting the parent object.
[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) }
Borrar todos los objetos de un tipo específico
Para eliminar todos los objetos de un tipo determinado de un dominio, pase el resultado de +[YourRealmObjectClass allObjectsInRealm:] a -[Realm deleteObjects:] dentro de una transacción de escritura. Reemplace YourRealmObjectClass
con el nombre de la clase de objeto Realm.
RLMRealm *realm = [RLMRealm defaultRealm]; [realm transactionWithBlock:^() { // Delete all instances of Dog from the realm. RLMResults<Dog *> *allDogs = [Dog allObjectsInRealm:realm]; [realm deleteObjects:allDogs]; }];
To delete all objects of a given object type from a realm, pass the result of Realm.objects(_:) for the type you wish to delete to Realm.delete(_:) inside of a write transaction.
let realm = try! Realm() try! realm.write { // Delete all instances of Dog from the realm. let allDogs = realm.objects(Dog.self) realm.delete(allDogs) }
Delete All Objects in a Realm
To delete all objects from the realm, call -[RLMRealm deleteAllObjects] inside of a write transaction. This clears the realm of all object instances but does not affect the realm's schema.
RLMRealm *realm = [RLMRealm defaultRealm]; [realm transactionWithBlock:^() { // Delete all objects from the realm. [realm deleteAllObjects]; }];
Para eliminar todos los objetos del dominio, llame a Realm.deleteAll() dentro de una transacción de escritura. Esto borra todas las instancias de objeto del dominio, pero no afecta su esquema.
let realm = try! Realm() try! realm.write { // Delete all objects from the realm. realm.deleteAll() }
Delete Map Keys/Values
Puedes eliminar entradas de mapa de varias maneras:
Usa
removeObject(for:)para remover la clave y el valor.If the dictionary's value is optional, you can set the value of the key to
nilto keep the key.
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"])
Borrar elementos de MutableSet
Puede eliminar elementos específicos de un MutableSet o borrar todos los elementos del conjunto. Si trabaja con varios conjuntos, también puede eliminar elementos de un conjunto del otro; consulte: Actualizar una propiedad de 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)
Borrar el valor de AnyRealmValue
To delete the value of an AnyRealmValue, set it to .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 }
Eliminar un objeto de forma asincrónica
Puede utilizar las funciones de concurrencia de Swift para eliminar objetos de forma asincrónica mediante un ámbito aislado del actor.
This function from the example RealmActor defined on the Use Realm with Actors page shows how you might delete an object in an 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!) } }
Y puedes realizar esta eliminación utilizando la sintaxis asíncrona de 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") }
This operation does not block or perform I/O on the calling thread. For more information about writing to realm using Swift concurrency features, refer to Use Realm with Actors - Swift SDK.