为什么清除领域 table 的内容会使 object 无效?

why does clearing contents of realm table invalidate the object?

我有一个收藏夹 table,我想做的是清除所有数据的 table,然后用数组的内容重新加载它。这是代码:

//empty FavouritesRealm table and reload favouritesArray back into FavouritesRealm
    let clearTable = realm.objects(FavouritesRealm)
    try! realm.write{
        for row in clearTable{
            realm.delete(row)
        }

        for f in favouritesArray{
            let favouriteRealm = FavouritesRealm()
            favouriteRealm.name = f.name
            favouriteRealm.price = f.price
            favouriteRealm.dbSource = f.dbSource
            favouriteRealm.date = f.date
            favouriteRealm.favourite = f.favourite
            realm.add(favouriteRealm)
        }
    }

现在,应用程序崩溃并显示以下评论: "Terminating app due to uncaught exception 'RLMException', reason: 'Object has been deleted or invalidated.'"

当所有行都被删除时,

Swift似乎删除了我的object(即table),但我只想清除所有数据。我该如何解决这个问题?

Realm 使用 zero-copy 方法,您可以检索 live-updating object 直接访问 memory-mapped 数据而不是副本的访问器。

根据错误消息,我假设 favouritesArray 中的 object 是托管领域 object。如果是这样的话,就没有必要 re-create 他们了。 Managed objects 只能在写入事务中修改,这意味着您的所有更改都会保留。与其尝试删除所有 object,然后删除 re-adding 收藏夹,在您的情况下,只删除不再受欢迎的 object 可能更容易

如果此数组包含尚未添加到领域的独立 object 和已添加到领域的托管 object,则 add(:_ update: true) 可以促进添加或更新您的 object 如果他们有主键。