Do you know this trick to spot memory leaks? 🤨
Hi 👋
It’s been quite a busy and exciting week-end for me: I’ve listed something for sale on Gumroad for the first time ever!
Today is a bank holiday in France, and I’m quite happy I have this extra day off to settle down and rest a bit 😌
But before I go enjoying my day off I want to share a pretty cool trick with you, that should help you notice more easily when a ViewController
starts to leak from memory!
This trick relies on a clever use of a feature in Xcode called Symbolic Breakpoints.
What is a Symbolic Breakpoint you might be wondering?
It’s quite similar to a regular breakpoint, except that its triggering mechanism isn’t linked to a line of code being executed, but rather to a method being called.
First, let me show you how to create a Symbolic Breakpoint in Xcode:
Then, the next step is to set the symbol that will trigger the breakpoint:
At this point, there’s a good chance that you might be wondering where this weird syntax comes from: -[UIViewController dealloc]
It actually comes from Objective-C!
Let me break it down for you:
“
-
” indicates that we’re dealing with an instance method“
[object method]
” is the Obj-C syntax for a method call“
UIViewController
” is the type we want to monitor“
dealloc
” is the Obj-C equivalent to “deinit
” in Swift
This means that were are defining a Symbolic Breakpoint that will trigger whenever an instance of UIViewController
(including its subclasses) gets released from memory 👍
After that, let’s add an action to this breakpoint:
I’ve added an action that will play a sound whenever the breakpoint is triggered. 🎶
To finish, I check the box so that the breakpoint will only execute its action and won’t actually stop the execution flow:
So what have we managed to achieve with this Symbolic Breakpoint?
We’ve basically created a nice mechanism that will play a sound whenever a ViewController
gets released from memory!
This should make it easier to spot a ViewController
leaking from memory: whenever you pop the navigation stack or close a modal, if you don’t hear the little sound then you’ll know there’s probably a memory leak in your code 🐛
(Of course, you can totally replace the little sound by a console print, if that works better for you 👍)
If you’re curious to see a demo of this trick in action, I can recommend you watch this video I made last year:
That’s all for this email, thanks for reading it!
If you’ve enjoyed it, feel free to forward it
to your friends and colleagues 🙌
I wish you an amazing week!
❤️