LLDB (http://lldb.llvm.org), described on the official webpage as a next generation, high-performance debugger, is the debugger that’s currently shipped with Xcode. Just a few years ago, LLDB replaced gdb, and now LLDB is the only debugger supported by Xcode. In this app developer tutorial, I will show you how to use the LLDB debugger and theexpression
command when developing iOS and watchOS apps.
You can run LLDB from the Terminal typing: xcrun lldb
. The xcrun
command points the Terminal to the LLDB version shipped with Xcode (the Xcode bundle contains tons of tools). If you omit the xcrun
command, the Terminal executes LLDB installed in the /usr/bin/
directory, which could contain a different version than the LLDB used by Xcode.
Unfortunately, executing LLDB from the Terminal app is only useful to debug apps that are not sandboxed. If you want to debug an iOS or watchOS app, you need to use LLDB from the Xcode console when executing the app with the Apple IDE. After compiling and running an app, you can access the LLDB console at any time by pressing the Pause button in the Xcode UI (see next figure).
The execution of the app is paused and LLDB attaches to it. At this point, you can type LLDB commands in the console, as you can see in the following picture.
You can learn more about the different LLDB commands by typing help
in the console or reading the documentation provided with Xcode. Another valuable resource is the previously mentioned LLDB webpage (http://lldb.llvm.org). If you want to know more about a particular command, just type help
in the console followed by the command name, and LLDB will print out the help for that particular command.
One of the LLDB commands is expression
and in this post, I will show you how to use expression
to debug Swift or Objective-C applications by injecting code at runtime and interacting with the objects of your app. You can also useexpression
in combination with the Xcode breakpoints, which I will show you later.
Evaluating Swift or Objective-C code
If you type help expression
in the console, you get the following description:
1
2
3
4
5
|
Evaluate
an
expression
(
ObjC
++
or
Swift
)
in
the
current
program
context
,
using
user
defined
variables
and
variables
currently
in
scope
.
This
command
takes
'raw'
input
(
no
need
to
quote
stuff
)
.
Syntax
:
expression
<
cmd
-
options
>
--
<
expr
>
|
As you can see, you can evaluate Objective-C++ and Swift expressions, using user defined variables and also variables within the scope. So let’s try to use the expression
command. First of all, if you don’t need any of the options provided by expression
, you can use the short form p
followed by the <expr>
that you want LLDB to evaluate. So, instead of writing:
1
|
(
lldb
)
expression
let
hello
=
"Hello"
|
you can simply use: