40

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.

CaptainCOOLGUY
  • 1,131
  • 1
  • 14
  • 26

4 Answers4

114

Use deleteAll():

let realm = try! Realm()
try! realm.write {
    realm.deleteAll()
}
Ryan Brodie
  • 6,554
  • 8
  • 40
  • 57
jpsim
  • 14,329
  • 6
  • 51
  • 68
  • 1
    Thanks, you guys should add that to the documentation! – CaptainCOOLGUY Oct 08 '14 at 03:09
  • 1
    This is documented in Realm's API docs: https://realm.io/docs/objc/latest/api/Classes/RLMRealm.html#//api/name/deleteAllObjects, which are more comprehensive than Realm's getting started documentation at https://realm.io/docs/objc/latest. – jpsim Nov 05 '15 at 18:34
  • 4
    I think the API changed a bit. For me to remove all objects using `RealmSwift`this worked: `try! realm.write { realm.deleteAll() }` – John B. Jun 07 '16 at 15:57
  • @JohnB. Updated answer. – Ryan Brodie Aug 24 '16 at 08:08
  • 1
    if the realm notification still running that time, it might cause crash, if directly use realm.deleteAll() – atom2ueki Mar 21 '17 at 07:41
16

As of v0.87.0, there is a deleteAllObjects method on RLRealm that will clear the Realm of all objects.

Michael McGuire
  • 3,770
  • 2
  • 29
  • 28
11

Things have moved on in the Realm world - in case anyone comes across this now, there is a property that can be set:

Realm.Configuration.defaultConfiguration.deleteRealmIfMigrationNeeded = true

It then does as advertised. (btw: a lot of the syntax above has changed in case you are trying any of the other methods)

The Github PR https://github.com/realm/realm-cocoa/pull/3463

David Glance
  • 619
  • 5
  • 8
5

I think removing the Realm DB file is the valid answer considering that the question was about removing a whole storage rather than migrating it.

Here is a quick Swift code for that (as of Swift 2.1 and Realm 0.96.2):

if let path = Realm.Configuration.defaultConfiguration.path {
    try! NSFileManager().removeItemAtPath(path)
}

I use this code in the DEBUG version of the app if the migration error happens on loading the storage and then I recreate the storage. During development the schema can change a lot, so it would be too cumbersome to bother with migration all the time.

zubko
  • 1,718
  • 25
  • 28