Swift Remove Object from Realm

后端 未结 6 1145
庸人自扰
庸人自扰 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 05:02

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

提交回复
热议问题