Swift Remove Object from Realm

这一生的挚爱 提交于 2019-12-31 21:29:35

问题


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

回答1:


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)



回答2:


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



回答3:


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
}



回答4:


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




回答5:


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


来源:https://stackoverflow.com/questions/40970582/swift-remove-object-from-realm

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