netshark1000 netshark1000 - 5 months ago 32
Swift Question

ObjectMapper + Realm + Alamofire

I map my objects with ObjectMapper, that are delivered by Alamofire and persist them in Realm.

Everthing is working fine. But how can I delete objects, that exist in Realm but have been deleted in my webservice?

Update: Based on the answer below I currently ended with this code:

if let overviewItemsArray = response.result.value{

do{
try self.realm.write{
self.realm.delete(self.realm.objects(OverviewItem))
self.realm.add(overviewItemsArray, update: true)
}
}
catch let err as NSError {
logger.error("Error with realm: \(err.localizedDescription)")
}
overviewItemsAsList.removeAll()
overviewItemsAsList.appendContentsOf(self.realm.objects(OverviewItem)
.sorted("sortOrder", ascending: true))
successHandler(overviewItemsAsList)
}


Perhaps somebody has further input how to improve this. I have 10 objects of this type. But on other objects I get 1500 items.

Answer

I finally figured it out and it works very well. I compute the difference of the cached data and the new data and delete it:

private func deleteOrphans(existingData: List<VotingHeader>, fetchedData:[VotingHeader]){

        guard existingData.count>0 else {
            return
        }

        let existingIDs = Set(existingData.map({$0.votingID}))
        let incomingIDs = fetchedData.map({$0.votingID})
        let idsToDelete = existingIDs.subtract(incomingIDs)

        if idsToDelete.count>0{
            let itemsToDelete =  self.realm.objects(VotingHeader).filter("votingID IN %@",idsToDelete)

            try! self.realm.write{
                self.realm.delete(itemsToDelete)
            }
        }
    }
Comments