Search code examples
swiftrealmalamofireobjectmapper

Alamofire, ObjectMapper, Realm: Delete orphaned objects


I use Alamofire, ObjectMapper and Realm and save my fetched and mapped objets in realm. Is it possible to delete orphaned objects automatically?

e.g. I fetch for a list of contacts. Now one contacts has been removed from the response and should be deleteted from Realm automatically. Is this something objectmapper can do?


Solution

  • I am not aware of a way to do it 'automatically' with Realm or ObjectMapper, but you could essentially delete orphaned objects by performing the Set.Subtract() operation on your Realm data. However, this also means you would have to conform to the Hashable protocol on your Realm class.

    Once you implement Hashable, you could do something like this:

    var contacts = try! Realm().objects(Contacts)
    
    let realmSet = Set<Contacts>(self.contacts)
    let incomingSet = Set<Contacts>(incomingContacts)
    let contactsToDeleteSet = realmSet.subtract(incomingSet)
    for contact in contactsToDeleteSet {
        try! realm.write {
            realm.delete(contact)
        }
    }
    

    You can check out all the awesome Set operations here: Performing Set Operations.