Skip to content
DeveloperMemos

How to Delete an Object with RealmSwift

RealmSwift, iOS Development1 min read

When working with data persistence in iOS development, it's common to encounter scenarios where you need to delete objects from your database. In this tutorial, we will focus on using RealmSwift, a powerful and easy-to-use database framework, to delete objects efficiently. We'll walk through the process step by step and provide code examples along the way.

Let's get started!

Prerequisites

To follow along with this tutorial, you'll need:

  1. Xcode installed on your Mac.
  2. Basic knowledge of Swift and iOS development.
  3. Familiarity with RealmSwift. If you're new to RealmSwift, consider checking out their documentation and setting up a basic project before proceeding.

Deleting an Object with RealmSwift

To delete an object using RealmSwift, you need to perform the following steps:

Step 1: Retrieve the Object

First, you must retrieve the object you want to delete from the Realm database. This typically involves querying the database based on specific criteria or fetching a particular object directly.

Here's an example that retrieves a Person object with a given ID:

1let realm = try! Realm()
2if let personToDelete = realm.object(ofType: Person.self, forPrimaryKey: personID) {
3 // The object exists, proceed with deletion
4} else {
5 // The object doesn't exist
6}

Step 2: Perform Deletion

Once you have the object you want to delete, you can call the delete(_:) method on the Realm instance to remove it from the database.

1try! realm.write {
2 realm.delete(personToDelete)
3}

The above code snippet deletes the personToDelete object from the Realm database within a write transaction. Remember to handle any potential errors appropriately, such as wrapping the deletion operation in a do-catch block.

Step 3: Handle Deletion Confirmation

After deleting the object, you may need to confirm its removal or update your user interface accordingly. You can check if the object still exists in the database by attempting to fetch it again:

1let deletedPerson = realm.object(ofType: Person.self, forPrimaryKey: personID)
2if deletedPerson == nil {
3 // The object was successfully deleted
4} else {
5 // Deletion failed
6}

In the example above, if deletedPerson is nil, it means the object was successfully deleted.