Docs 菜单
Docs 主页
/ /
Atlas Device SDKs
/ /

CRUD - 删除 - Swift SDK

在此页面上

  • 删除 Realm 对象
  • 关于本页中的示例
  • 删除对象
  • 删除多个对象
  • 删除某一对象及其相关对象
  • 删除特定类型的所有对象
  • 删除 Realm 中的所有对象
  • 删除映射键/值
  • 删除 MutableSet 元素
  • 删除 AnyRealmValue 的值
  • 异步删除对象

删除 Realm 对象必须在写事务中进行。有关写入事务的更多信息,请参阅:事务

如果您要删除 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 {
@Persisted var name = ""
@Persisted var age = 0
@Persisted var color = ""
@Persisted var currentCity = ""
@Persisted var citiesVisited: MutableSet<String>
@Persisted var companion: AnyRealmValue
// Map of city name -> favorite park in that city
@Persisted var favoriteParksByCity: Map<String, String>
}

要从域中删除对象,请将该对象传递给写事务(write transaction)内的 -[RLMKRealm deleteObject:]

[realm transactionWithBlock:^() {
// Delete the instance from the realm.
[realm deleteObject:dog];
}];

要从一个域中删除一个对象,请将此对象传递给一个写事务内部的 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.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.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)
}

要从域中删除对象集合,请将该集合传递给写事务(write transaction)中的-[ 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)
}

要从域中删除给定对象类型的所有对象,请在写事务(write transaction)内将+[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.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)
}

要从域中删除所有对象,请在写事务(write transaction)中调用-[RLMRealm deleteAllObjects] 。 这会清除域中的所有对象实例,但不影响 Realm 的模式。

RLMRealm *realm = [RLMRealm defaultRealm];
[realm transactionWithBlock:^() {
// Delete all objects from the realm.
[realm deleteAllObjects];
}];

要从 Realm 中删除所有对象,请调用Realm.deleteAll() 写事务中。 这会清除 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 属性。

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
}

您可以使用 Swift 并发功能,通过 actor 隔离的 Realm 来异步删除对象。

这个函数来自“结合使用 Realm 与 Actor”页面中给出的示例 RealmActor 中的函数,显示了如何在 actor 隔离的 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 与 Actor - Swift SDK

后退

Update