why does clearing contents of realm table invalidate the object?

旧街凉风 提交于 2019-12-25 04:45:18

问题


I have a table for favourites and what I want to do is to clear the table of all data and then reload it with the contents of an array. Here is the code:

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

Now, the app crashes with the comment: "Terminating app due to uncaught exception 'RLMException', reason: 'Object has been deleted or invalidated.'"

Swift seems to delete my object (which is the table) when all rows are deleted, but I just want to clear all data. How can I get around this?


回答1:


Realm is using a zero-copy approach where you retrieve live-updating object accessors which directly access memory-mapped data instead of copies.

Based on the error message, I assume that the objects in favouritesArray are managed Realm objects. If that's the case, there would be no need to re-create them. Managed objects can only be modified within write transactions, which implies that all your changes are persisted. Instead of trying to delete all objects and then re-adding the favorites, it might be easier in your case to delete just the objects which are not favored anymore

If this array contains standalone objects, which were not added to a Realm yet and managed objects, which are already added to a Realm, then add(:_ update: true) can facilitate to add or update your objects if they have a primary key.



来源:https://stackoverflow.com/questions/38068826/why-does-clearing-contents-of-realm-table-invalidate-the-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!