37

我可以选择进行迁移,但我更愿意删除我的 defaultRealm() 中的所有内容。我怎样才能轻松做到这一点?

realm.deleteObject(object)

是与 .deleteObjects 一起的唯一功能。

我尝试了以下代码:

方法一

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

方法二

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

两者都未能防止迁移异常。

4

4 回答 4

106

使用deleteAll()

let realm = try! Realm()
try! realm.write {
    realm.deleteAll()
}
于 2014-10-07T20:37:12.803 回答
15

v0.87.0 开始,有一种deleteAllObjects方法RLRealm可以清除所有对象的领域。

于 2014-10-23T16:17:52.440 回答
11

Realm 世界中的事情已经发生了变化——如果有人现在遇到这种情况,可以设置一个属性:

Realm.Configuration.defaultConfiguration.deleteRealmIfMigrationNeeded = true

然后它会像宣传的那样做。(顺便说一句:如果您尝试任何其他方法,上面的很多语法已经改变)

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

于 2016-06-03T12:27:43.817 回答
5

考虑到问题是关于删除整个存储而不是迁移它,我认为删除 Realm DB 文件是有效的答案。

这是一个快速的 Swift 代码(从 Swift 2.1 和 Realm 0.96.2 开始):

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

如果在加载存储时发生迁移错误,我会在应用程序的 DEBUG 版本中使用此代码,然后我重新创建存储。在开发过程中,模式可能会发生很大变化,因此一直为迁移而烦恼太麻烦了。

于 2015-11-08T13:08:04.050 回答