Swift Remove Object from Realm

后端 未结 6 1227
庸人自扰
庸人自扰 2021-02-04 04:06

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 f

6条回答
  •  自闭症患者
    2021-02-04 04:45

    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
    }
    

提交回复
热议问题