netshark1000 netshark1000 - 8 months ago 53
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{

try self.realm.write{
self.realm.add(overviewItemsArray, update: true)
catch let err as NSError {
logger.error("Error with realm: \(err.localizedDescription)")
.sorted("sortOrder", ascending: true))

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


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 {

        let existingIDs = Set({$0.votingID}))
        let incomingIDs ={$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{