How can I easily delete all objects in a Realm

CaptainCOOLGUY picture CaptainCOOLGUY · Oct 3, 2014 · Viewed 48.1k times · Source

I have the choice of doing a migration, but I would prefer to delete everything in my defaultRealm(). How can I do this easily?

realm.deleteObject(object)

is the only function along with .deleteObjects.

I have tried the following code:

Method 1

realm.deleteObjects(RLMObject.objectsInRealm(realm, withPredicate: NSPredicate(value: true)))

Method 2

        realm.deleteObjects(Dog.allObjectsInRealm(realm))
        realm.deleteObjects(Person.allObjectsInRealm(realm))
        realm.deleteObjects(Goal.allObjectsInRealm(realm))
        realm.deleteObjects(Goals.allObjectsInRealm(realm))

Both fail to prevent the migration exception.

Answer

jpsim picture jpsim · Oct 7, 2014

Use deleteAll():

let realm = try! Realm()
try! realm.write {
    realm.deleteAll()
}