Home > front end >  Do functions given to the escaping closures create strong reference to the functions owner instance
Do functions given to the escaping closures create strong reference to the functions owner instance

Time:12-08

I have massive memory leaks in the project I am currently working on. The VC's never disappear from the memory and unfortunately that causes many, many problems right now. The only culprit that I can think of is the way I use closures in the name of readability and simplicity since none of those closures captures self strongly inside. The way I use is as following:

functionWithEscapingClosure(closure: functionGivenToTheClosure(_:))

If this creates a strong reference I have soo many refactoring to do, if not I will look elsewhere. Thanks in advance!

I have looked for an explanation to the subject online, searched through the Swift documentation but couldn't find any information.

CodePudding user response:

Your snippet there is essentially equivalent to:

functionWithEscapingClosure(closure: { parameter in
    self.functionGivenToTheClosure(parameter)
})

So yes, it would implicitly capture a strong reference to the instance that owns the function passed in.

You would need to explicitly do the weak capture to break the cycle:

functionWithEscapingClosure(closure: { [weak self] parameter in
    self?.functionGivenToTheClosure(parameter)
})
  • Related