CaptainCOOLGUY CaptainCOOLGUY - 6 months ago 170
Swift Question

How can I easily delete all objects in a Realm

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

It's easy to delete the Realm file at app launch:~~

NSFileManager.defaultManager().removeItemAtPath(defaultRealmPath(), error: nil)

However, this code is only safe to run before any instances of RLMRealm are created. So you should run this at the start of application(application:didFinishLaunchingWithOptions:).

As of 0.87.0 as Michael McGuire mentions below there is a deleteAllObjects method

let realm = RLMRealm.defaultRealm()
realm.beginWriteTransaction()
realm.deleteAllObjects()
realm.commitWriteTransaction()
Comments