Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate table in Realm Swift

I am trying to delete all objects inside one class. I found two possibilities inside Realms documentation. First there's the possibility to use realm.deleteAll(), which deletes the whole database and there's realm.delete(), which deletes one single object. Is there a way to delete all entries inside one Table/Class in a easy way?

like image 616
Fabio ha Avatar asked Nov 14 '25 09:11

Fabio ha


2 Answers

Suppose you want to delete all objects of Notofications,

you can try this

let realm = Realm()
    realm.write {
      let allNotifications = realm.objects(Notifications)
      realm.delete(allNotifications)
    }
like image 162
Er. Khatri Avatar answered Nov 17 '25 09:11

Er. Khatri


Here's an extension that does this:

extension Object {
    static func deleteAll(`in` realm: Realm) throws {
        let allObjects = realm.objects(self)
        try realm.write {
            realm.delete(allObjects)
        }
    }
}
like image 36
Sweeper Avatar answered Nov 17 '25 08:11

Sweeper