The weak delegate becomes zero

In my application, I use delegates so that I can read the data when it was ready.

I am calling a delegate from two classes. Here is my code

protocol MyDelegate: class {
    func getData()
}

class MyDelegateCalss {

     weak var delegate: MyDelegate?    
     func loadData() {

        // doing some actions        

         if(self.delegate != nil){
            self.delegate!.getData!()
        }
    }
}

In one class, I load this method in the delegate method of the numberOfSections tableview.

class A: UIViewController, MyDelegate {


    func somefunc(){
        let mydelegatecls : MyDelegateCalss = MyDelegateCalss()
        mydelegatecls.delegate = self
        mydelegatecls.loadData()
    }


    func getData(){
       // Doing some actions
    }
}

I load this method from other calss.

class B: UIViewController, MyDelegate {


   open func testfunc(){

    let mydelegatecls : MyDelegateCalss = MyDelegateCalss()
      mydelegatecls.delegate = self
      mydelegatecls.loadData()
   }



    func getData(){
      // doing some other stuff    
    }

}



class C: UIViewController {

       func testfunc(){

        let b : B = B()
          b.testfunc()
       }
    }

Here from class A, my delegate is working fine. and I can see the getData method calls.

from class B, the delegate becomes nil and cannot see that the getData method is called

If I give the delegate a link to his work. But this will cause a memory leak.

How to deal with this case?

+6
source share
1 answer

delegate var weak. , ( MyDelegate), delegate nil, (, , ).

: https://cocoacasts.com/how-to-break-a-strong-reference-cycle/

+3

Source: https://habr.com/ru/post/1016794/


All Articles