Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Remove Object from Realm

Tags:

xcode

swift

realm

I have Realm Object that save list from the JSON Response. But now i need to remove the object if the object is not on the list again from JSON. How i do that? This is my init for realm

func listItems (dic : Array<[String:AnyObject]>) -> Array<Items> {
        let items : NSMutableArray = NSMutableArray()
        let realm = try! Realm()
        for itemDic in dic {
            let item = Items.init(item: itemDic)
                try! realm.write {
                    realm.add(item, update: true)
                }
            items.addObject(item)
        }
        return NSArray(items) as! Array<Items>
}
like image 662
Voyager Avatar asked Dec 05 '16 09:12

Voyager


3 Answers

imagine your Items object has an id property, and you want to remove the old values not included in the new set, either you could delete everything with just

let result = realm.objects(Items.self)
realm.delete(result)

and then add all items again to the realm, or you could also query every item not included in the new set

let items = [Items]() // fill in your items values
// then just grab the ids of the items with
let ids = items.map { $0.id }

// query all objects where the id in not included
let objectsToDelete = realm.objects(Items.self).filter("NOT id IN %@", ids)

// and then just remove the set with
realm.delete(objectsToDelete)
like image 85
fel1xw Avatar answered Nov 18 '22 01:11

fel1xw


I will get crash error if I delete like top vote answer.

Terminating app due to uncaught exception 'RLMException', reason: 'Can only add, remove, or create objects in a Realm in a write transaction - call beginWriteTransaction on an RLMRealm instance first.'

Delete in a write transaction:

let items = realm.objects(Items.self)
try! realm!.write {
    realm!.delete(items)
}
like image 11
William Hu Avatar answered Nov 17 '22 23:11

William Hu


func realmDeleteAllClassObjects() {
    do {
        let realm = try Realm()

        let objects = realm.objects(SomeClass.self)

        try! realm.write {
            realm.delete(objects)
        }
    } catch let error as NSError {
        // handle error
        print("error - \(error.localizedDescription)")
    }
}

// if you want to delete one object

func realmDelete(code: String) {

    do {
        let realm = try Realm()

        let object = realm.objects(SomeClass.self).filter("code = %@", code).first

        try! realm.write {
            if let obj = object {
                realm.delete(obj)
            }
        }
    } catch let error as NSError {
        // handle error
        print("error - \(error.localizedDescription)")
    }
}
like image 9
BatyrCan Avatar answered Nov 18 '22 01:11

BatyrCan