Search code examples
iosrealm

Realm database - Notification when deleting an object


My question is simple: Is there some way for an instance of an object to be notified when it's about to get deleted?

I have a case where I have a property that is the path to an image stored on disk. I would like to delete this image whenever a realm object of that type is deleted.


Solution

  • If you prefer not to use KVO, you can take advantage of Realm's Object Notifications.

    A brief example would be:

    var token: NotificationToken?
    token = yourRealmObject.addNotificationBlock { change in
        switch change {
        case .change(let properties):
            print("Object has changed")
        case .error(let error):
            print("An error occurred: \(error)")
        case .deleted:
            print("The object was deleted.")
        }
    }
    

    just make sure to retain a strong reference to the token object since your notification block will be automagically unsubscribed by Realm as soon as it is released.