删除特定Realm Object Swift中的所有数据

Yic*_*man 14 persistence realm swift

在我深入研究我的问题之前.我的目标可能会影响您的答案,Object如果数据不再存在于云中,则会删除数据.

所以,如果我有一个数组 ["one", "two", "three"]

然后在我的服务器中删除 "two"

我希望我的领域能够更新变化.

我认为最好的方法是删除特定的所有数据Object,然后调用我的REST API下载新数据.如果有更好的方法,请告诉我.

好的,这是我的问题.

我有一个对象 Notifications()

每次调用我的REST API时,在下载任何我正在运行的内容之前:

let realm = Realm()
let notifications = Notifications()
realm.beginWrite()
realm.delete(notifications)
realm.commitWrite()
Run Code Online (Sandbox Code Playgroud)

运行后我收到此错误: Can only delete an object from the Realm it belongs to.

所以我尝试过这样的事情:

for notification in notifications {
    realm.delete(notification)
}
realm.commitWrite()
Run Code Online (Sandbox Code Playgroud)

我在xcode中得到的错误是这样的: "Type Notifications does not conform to protocol 'SequenceType'

不确定从哪里开始.

只是想弄清楚领域.完全是新的

注意:realm.deleteAll()有效,但我不希望我的所有领域都被删除,只是确定Objects

jps*_*sim 26

你在找这个:

let realm = Realm()
let deletedValue = "two"
realm.write {
  let deletedNotifications = realm.objects(Notifications).filter("value == %@", deletedValue)
  realm.delete(deletedNotifications)
}
Run Code Online (Sandbox Code Playgroud)

或许这个:

let realm = Realm()
let serverValues = ["one", "three"]
realm.write {
  realm.delete(realm.objects(Notifications)) // deletes all 'Notifications' objects from the realm
  for value in serverValues {
    let notification = Notifications()
    notification.value = value
    realm.add(notification)
  }
}
Run Code Online (Sandbox Code Playgroud)

虽然理想情况下,您将设置主键,Notifications以便您可以简单地更新这些现有对象,而不是采用极端方法来对所有本地对象进行核对,只需重新创建它们(或几乎).