How to delete Object with its Realm List


#1

Hi ,

I have Realm object and Realm list that related to each other
I want when I delete Realm Object it also Delete RealmList

For now I use

  func deleteRealmObjectById(id:String){
        do {
            let realm = try Realm()
            
            
            let dataWillSendObjectDelete = dataWillSendObject.filter("id == %@",id)
            
            
            try realm.write {
                realm.delete(dataWillSendObjectDelete)
            }
 
            
        }catch {
            print("there is error with delete Realm object ! : \(error)")
        }
    }

you can see this image the RecodsFoward object it deleted and become 1
but the attachments is remind 3

I need when I delete RecodsFoward object I also delete attachments

My Model is like this

class RecordsForward:Object{
    
    @objc dynamic var id: String?
    @objc dynamic var type: Int = 0
    @objc dynamic var recTitle: String?
    @objc dynamic var toUserID: String?
    @objc dynamic var direction: Int = 1
    var Attachments = List<attachments>()
}

class attachments : Object {
    
    @objc dynamic var name: String = ""
    @objc dynamic var recId: Int = 0
    @objc dynamic var typeId = 2
    @objc dynamic var contents: String = ""
    }


#2

Depend on this Answer

I need to delete the object child (List) before delete parent object

so I change the code to this

  func deleteRealmObjectById(id:String){
        do {
            let realm = try Realm()
            
            
            let dataWillSendObjectDelete = dataWillSendObject.filter("id == %@",id)
            
            guard let attachmentObject =  dataWillSendObjectDelete.first?.Attachments.first else {return print("cannot delete child")}
            
            try realm.write {
                realm.delete(attachmentObject)
                realm.delete(dataWillSendObjectDelete)
            }
 
            
        }catch {
            print("there is error with delete Realm object ! : \(error)")
        }
    }

after some test I think it’s the correct solution
it works fine !