【问题标题】:Delete all data from specific Realm Object Swift从特定领域对象 Swift 中删除所有数据
【发布时间】:2015-05-28 18:29:22
【问题描述】:

在我深入探讨我的问题之前。我的目标可能会影响您的回答,如果 Object 数据不再在云中,则将其删除。

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

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

我希望我的领域更新更改。

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

好的,这是我的问题。

我有一个对象Notifications()

每次调用我的 REST API 时,在它下载任何我运行的东西之前:

let realm = Realm()
let notifications = Notifications()
realm.beginWrite()
realm.delete(notifications)
realm.commitWrite()

运行后出现此错误:Can only delete an object from the Realm it belongs to.

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

for notification in notifications {
    realm.delete(notification)
}
realm.commitWrite()

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

不确定从这里去哪里。

只是想弄清楚领域。对它完全陌生

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

【问题讨论】:

    标签: swift persistence realm


    【解决方案1】:

    你正在寻找这个:

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

    或者这个:

    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)
      }
    }
    

    虽然理想情况下,您应该在Notifications 上设置一个主键,这样您就可以简单地更新那些现有的对象,而不是采取极端的方法来消除所有本地对象来重新创建它们全部(或几乎)。

    【讨论】:

      最近更新 更多