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...

Display Name
  • 4,502
  • 2
  • 47
  • 63
  • 4
    There is no distinct closure syntax and not all closures cause retain cycles (for example GCD (a)sync DispatchQueue closures don't) – vadian Feb 27 '18 at 17:31
  • 2
    You might take a look at https://github.com/yanagiba/swift-ast - you can create the abstract syntax tree and look out for `ClosureExpression`s. I've not tried this yet, but if you find out something, you could inform us if it was helpful or not :-) – Andreas Oetjen Feb 27 '18 at 17:46
  • 3
    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. – Rob Feb 27 '18 at 17:51
  • 2
    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. – Rob Feb 27 '18 at 18:01
  • 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. – Display Name Feb 27 '18 at 19:21
  • 2
    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://stackoverflow.com/a/30993476/1271826). It's a lot easier to find strong reference cycles that way rather than profiling with Instruments, IMHO. – Rob Feb 27 '18 at 22:47

0 Answers0