Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to check reference count for an object

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?

like image 404
peacetype Avatar asked Dec 04 '22 18:12

peacetype


2 Answers

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.

Steps

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.

lldb console prompt

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)

More About Debugger Commands

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

like image 84
peacetype Avatar answered Dec 29 '22 05:12

peacetype


Just type po CFGetRetainCount(someVariable) on lldb

Source: https://developer.apple.com/documentation/corefoundation/1521288-cfgetretaincount

like image 29
Bruno Cunha Avatar answered Dec 29 '22 04:12

Bruno Cunha