user7925427
user7925427

Reputation:

Weak delegate becomes nil

In my app I'm using delegates, so that I can read the data when ever it's ready.

I'm 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'm loading this method in tableview numberOfSections delegate method.

class A: UIViewController, MyDelegate {


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


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

This method I'm loading from another 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'm able to see getData method is calling .

from Class B, the delegate becomes nil and unable to see getData method is called

If I make the delegate reference its working fine. But that will cause memory leak.

How can handle this case ?

Upvotes: 5

Views: 4434

Answers (1)

Loos
Loos

Reputation: 76

Your delegate var is declared as weak. If nothing keep a strong reference on the object you assign as the delegate (implementing MyDelegate), your delegate will pass to nil as soon as the object is released (eg. the end of the scope where you instantiate it).

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

Upvotes: 6

Related Questions