How can I find all closures?
Asked Answered
S

0

7

We've totally forgotten to capture self and its properties when referencing it within a closure. (Note: the compiler didn't warn us.) Now our application is full with strong reference cycles. To fix them, we have to add the capture list to each closure one-by-one.

How can we find them all? I thought to search for in but it results in too much results including comments, for cycles.

Good old Objective C would help me searching for ^. And it would warn us...

Sepoy answered 27/2, 2018 at 17:22 Comment(6)
There is no distinct closure syntax and not all closures cause retain cycles (for example GCD (a)sync DispatchQueue closures don't)Bombastic
You might take a look at github.com/yanagiba/swift-ast - you can create the abstract syntax tree and look out for ClosureExpressions. I've not tried this yet, but if you find out something, you could inform us if it was helpful or not :-)Bolshevist
BTW, when you searched for in, did you tell Xcode to use "matching word" rather than "contains". That can reduce false positives. Or you can do regular expression search and then specify to find only those occurrences of in that appear at the end of a line: \bin\s*$. That won't catch inline closures or those missing in altogether, but might find a certain percentage of your closures. You can alter that regex as you see fit to be tailored for the sort of patterns you employed in your project.Harmon
I know you're looking for a way to find closures, but obviously the other approach would be to run the app and use "debug memory graph" feature to fine those strong reference cycles. And if you use the "malloc stack" diagnostic setting so that when you find a strong reference cycle, you can see the call tree where the cycle was introduced. Some sleuthing will still be required, but that's a super efficient way to find and diagnose strong reference cycles.Harmon
I could find a lot with your RegEx, thank you! Profiling the app would take a lot of time and might cover less than the RegEx. I hope, Apple will introduce some warning in the near future to handle this.Sepoy
Very good. BTW, I'm not suggesting profiling the app with Instruments. In Xcode there is a "debug memory graph" feature (see the first half of the answer at https://mcmap.net/q/110608/-how-to-debug-memory-leaks-when-leaks-instrument-does-not-show-them). It's a lot easier to find strong reference cycles that way rather than profiling with Instruments, IMHO.Harmon

© 2022 - 2024 — McMap. All rights reserved.