ios 如何轻松删除 Realm 中的所有对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26185679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I easily delete all objects in a Realm
提问by CaptainCOOLGUY
I have the choice of doing a migration, but I would prefer to delete everything in my defaultRealm(). How can I do this easily?
我可以选择进行迁移,但我更愿意删除我的 defaultRealm() 中的所有内容。我怎样才能轻松做到这一点?
realm.deleteObject(object)
is the only function along with .deleteObjects.
是与 .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.
两者都无法防止迁移异常。
回答by jpsim
回答by Michael McGuire
As of v0.87.0, there is a deleteAllObjects
method on RLRealm
that will clear the Realm of all objects.
从v0.87.0 开始,有一种deleteAllObjects
方法RLRealm
可以清除所有对象的 Realm。
回答by David Glance
Things have moved on in the Realm world - in case anyone comes across this now, there is a property that can be set:
Realm 世界中的事情已经发生了变化 - 如果现在有人遇到这个问题,可以设置一个属性:
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
回答by zubko
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.
考虑到问题是关于删除整个存储而不是迁移它,我认为删除 Realm DB 文件是有效的答案。
Here is a quick Swift code for that (as of Swift 2.1 and Realm 0.96.2):
这是一个快速的 Swift 代码(从 Swift 2.1 和 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.
如果在加载存储时发生迁移错误,我会在应用程序的调试版本中使用此代码,然后我重新创建存储。在开发过程中,模式可能会发生很大变化,因此一直困扰着迁移会很麻烦。