In an iOS project using Xcode and Swift, is there a simple way to check the reference count for an object? Automatic Reference Counting (ARC) usually handles memory management for us, but I'm having trouble tracking down a memory leak in my app. I want an easy way to examine the reference count of any object at any given point in the app's lifecycle. Is there a simple way to do that?
I found an easy way using a command for the LLDB debugger console. If anyone knows another good way to examine the reference count of an object, feel free to leave another answer.
First, use a breakpoint to pause execution at a point in your code when you want to check the reference count of some object. The console will display (lldb)
. Click next to it to insert your cursor.
Type language swift refcount array
(where "array" is the name of the object that I wanted to examine; substitute the name of your own object instead), and then press Return. The console will output the object's reference count in this format:
refcount data: (strong = 1, unowned = 0, weak = 0)
Enter help
to see more console commands. There are a lot of them. I've been using Xcode for five years and I only just learned of them today. This can be a super useful debugging tool. FYI, here are a few of the most useful ones:
po self
Stands for "print-object". Prints a nice description of an object. I'm just using "self" here as an example. You can substitute the name of your own object.
p self
The "print" command. As print-object, but more verbose. Using "self" here as an example again.
step
Advance one line of code.
continue
Resume program execution.
expr
The "expression" command. Lets you enter Swift code to modify variables. For example, add some data to an array object:
expr array.insert(343, at: 0)
You can even change UI elements this way, as in this example:
expr self.view.tintColor = UIColor.red
Just type po CFGetRetainCount(someVariable)
on lldb
Source: https://developer.apple.com/documentation/corefoundation/1521288-cfgetretaincount
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With