Swift Remove Object from Realm

倖福魔咒の 提交于 2019-12-03 06:08:52
fel1xw

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)

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)
}

What you can do is assign a primary key to the object you are inserting, and when receiving a new parsed JSON you verify if that key already exists or not before adding it.

class Items: Object {
    dynamic var id = 0
    dynamic var name = ""

    override class func primaryKey() -> String {
        return "id"
    }
}

When inserting new objects first query the Realm database to verify if it exists.

let repeatedItem = realm.objects(Items.self).filter("id = 'newId'")

if !repeatedItem {
   // Insert it
}

The first suggestion that comes to mind is to delete all objects before inserting new objects from JSON.

Lear more about deleting objects in Realm at https://realm.io/docs/swift/latest/#deleting-objects

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)")
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!