Search code examples
realmrealm-mobile-platformrealm-list

Delete objects that does not belong from list - Realm


I have a new list of objects to be saved/updated in realm. I want first to delete all objects stored in realm that is not included in my new list before saving/updating the new ones. Any idea on how to do this? (I don't want to delete all my table rows first then save the new ones)


Solution

  • First of all welcome to StackOverflow & please follow what @teun-van-der-wijst has mentioned in the comments.

    Coming to your question,

    In realm there is no specific function to UPDATE an object. There are 2 ways you can perform an update.

    • Delete all the rows of the object and add the new ones. (But since you have mentioned that you do not wish to do this try option 2)
    • Use the WRITE method to assign a new value to a existing property by using a filter or predicate.

    You can follow this link for the documentation: https://realm.io/docs/swift/latest/#updating-objects

    This is just a generic example of how to update using WRITE

    let fruits = realm.objects(Fruits.self).filter("date = %@", removeTodaysItem)
    
    let realm = try! Realm()
    if let fruit = fruits.first {
        try! realm.write {
            fruit.date = "today's date"
        }
    }