Search code examples
swiftrealm

Delete a Realm model with Swift


I need to remove old, empty models from a Realm Cocoa database.

There seems to be a way to do it in Java, but not in Swift. Is that correct?

If you remove a property and initiate a migration Realm will remove the corresponding column in the table:

class Dog: Object {
  dynamic var name = ""
  // dynamic var age = 0
}

But, if you remove the model definition entirely, the migration does not remove the table:

// class Dog: Object {
//   dynamic var name = ""
//   dynamic var age = 0
// }

Here's a screenshot from Realm Browser showing the empty tables I want to delete:

realm browser empty tables


Solution

  • You can call Migration.deleteData(_:) within your migration block to specify that the named class should be completely removed from your Realm file.