How can I easily delete all objects in a Realm

ε祈祈猫儿з 提交于 2019-11-28 08:05:56
jpsim

Use deleteAll():

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

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

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

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!