ViewController passed as parameter is not being deinitialized (Swift)

62 views Asked by At

Setup: I have a ViewController ProblemView and class A. I pass ProblemView to class A, so I can work on it. It looks like this (simplified):

class ProblemView: UIViewController{
    var instanceOfA = A()
    instanceOfA.passView(passedVC: self)
}

class A{
    var workOn = ProblemView()

    func passView(passedVC: ProblemView){
        workOn = passedVC
        // I noticed, if I declare a varible locally like var workOn2 = passedVC, my problem is solved - 
        // but I need the variable globally, because I don't want to pass it around within this class
    }
    func doSth(){
        // here I interact with variables of the passed ViewController
    }
}

Problem: Whenever I restart this process within the app the memory increases every single time until I get memory error.

What I tried: I added deinit to both classes. class A is always deinitialized but class ProblemView is not (this might be the problem?). I also found out, that when I don't declare workOn globally but within the passView function, then it works just fine. But I need have the variable globally, because I use it within many different functions of A. What could be a solution or workaround to this problem?

1

There are 1 answers

1
Yuriy Troyan On BEST ANSWER

Strong references to each other.

Try to change class A:

weak var workOn: ProblemView?

func passView(passedVC: ProblemView){
    workOn = passedVC
    // I noticed, if I declare a varible locally like var workOn2 = passedVC, my problem is solved - 
    // but I need the variable globally, because I don't want to pass it around within this class
}
func doSth(){
    // here I interact with variables of the passed ViewController
}