Search code examples
swiftrealmdelete-row

why does clearing contents of realm table invalidate the object?


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?


Solution

  • 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.