Debugging in AppCode
In this tutorial, we will cover both basic and advanced features of the AppCode debugger. You will learn how to halt a program execution using different types of breakpoints, examine the paused program state, step through the code, alter the program behavior without exiting the debugger session, and so on.
Watch the video tutorial and follow the step-by-step instructions below:
As an example, we will take a simple SwiftUI application that loads a list of conferences from a local JSON file. You can look at how it was developed in the Create a SwiftUI application tutorial.
At the moment, this application contains some bugs that we are going to find and fix using the AppCode debugger. Download the project and run it by pressing Shift+F10 or clicking the button on the main toolbar.
Set an exception breakpoint and inject code at runtime
Problem
Right on the first start, the application crashes with the following error in the console of the Run tool window:
Solution
Let's set an exception breakpoint to locate the code that throws this error:
Set an exception breakpoint
From the main menu, select
or press Ctrl+Shift+F8.In the Breakpoints dialog that opens, select the Exception Breakpoints checkbox on the left. This will enable a default exception breakpoint which hits if any exception is thrown:
Click Done to apply the changes and start a debugging session by pressing Shift+F9 or clicking on the toolbar.
The program execution will stop at the line that throws the error, and the Debug tool window will appear:
The Threads & Variables tab displays a stack of method/function calls on the left and a list of variables available in the current context on the right.
The error that we’ve got (Expected to decode Double but found a string/data instead) most likely relates to the JSONDecoder
object stored in the decoder
variable. You can see all the properties of the JSONDecoder
object when expanding this variable. If the value is truncated, click View to open it in a popup:
We see that our JSONDecoder
uses the deferredToDate
decoding strategy that can handle dates in double format only, whereas we have string date values in our JSON.
Let's try to use the formatted
decoding strategy instead by injecting new code at runtime.
Inject code at runtime
Set a breakpoint right before the
decode()
method is called, namely, at the following line:return try decoder.decode(T.self, from: data)Press Ctrl+Shift+F8 to open the Breakpoints dialog.
In the Breakpoints dialog, select the line breakpoint at line 25 and check the Evaluate and log option.
In this field, you can type the code that you want to execute when the breakpoint is hit. Click to expand the text field and type the following code:
let formatter = DateFormatter() formatter.dateFormat = "yyyy-mm-dd" decoder.dateDecodingStrategy = .formatted(formatter)For the symbols visible in the current context, auto-completion is available:
Click Done and rerun the program in debug mode by pressing Ctrl+F5 or clicking the button on the Debug tool window.
Now when the application is suspended, you see the decoder.dateDecodingStrategy
property has a new value which cannot be displayed correctly on the Threads & Variables tab:
You can use the LLDB console to see such values. Go to the LLDB tab and type the following command:
Our decoder uses the formatted
date decoding strategy now:
Press F8 to step over to the next code line and go back to the Threads & Variables tab. The conferencesData
variable now stores the values from the parsed JSON file:
Resume the program by pressing F9 and make sure that the list of conferences is now displayed on your device or simulator:
Since the code injected on the breakpoint hit has fixed the bug, you can add it in the editor:
Delete the breakpoint at line 25 by clicking its icon.
Set variable values
Problem
Rerun the application Shift+F10 and select the dot Swift conference. The application will crash with the following error:
Solution
Let's fix this bug by setting a new variable value at runtime.
Go to the file and line specified in the error message (press Ctrl+Shift+N and type <filename>:<line number>), set a line breakpoint Ctrl+F8 at the first line of the
textDates()
method, and press Shift+F9.On the device or simulator screen, select the dot Swift conference to reproduce the bug. On the Variables tab and in the editor, you can see that the end date of the chosen conference equals
nil
:So, we see that the application is going to crash after executing line 17, more precisely, when trying to unwrap an optional value:
end!.dateToString()Let’s try to set a non-nil value for the
end
variable to ensure that it is the reason for the bug. Select theend
variable on the Variables tab and press F2. In the text field that appears, typeDate()
, press Enter, and press F8 or click to execute line 17.The application doesn’t crash now because we’ve set the current day as a value of the
end
property:To fix this bug, replace the code of the
textDates()
method with the following:func textDates() -> String { var result = start.dateToString() if let end = self.end { result = "\(result) - \(end.dateToString())" } return result }Run the application and check that now the dot Swift conference description opens without errors.
Set conditional breakpoints and add variables to watches
Problem
When selecting the Mobilization conference, you may notice that the day is displayed this way:
Solution
This happens because the textDates()
method doesn’t handle the conferences with the same start and end dates correctly. Let's add a conditional breakpoint that will stop the program execution only when calling textDates()
for one-day conferences. For convenience, we will display the conference data on the Watches tab.
Set a new breakpoint at line 21 (Ctrl+F8) and remove the previous one at line 17 by clicking its icon in the gutter.
We want the new breakpoint to stop the program execution only when the end and start dates of the conference are the same. For this purpose, we can create a special condition: right-click the breakpoint and in the Condition field type
end == start
:Run the application in debug mode Shift+F9 and select random conferences from the list. The program execution will stop only when the specified condition is satisfied, for example, on selecting the Mobilization conference:
Now when the program is paused, and the Debugger tab is available, let’s add the
result
variable to watches, which will allow us to observe the variable state in a separate tab. To do this, right-click the variable on the Variables tab and select Add to Watches. If the Watches tab is currently hidden, click the button and select Watches in the list.You can add any variable you want to observe to watches. For example, you can also add the
name
variable to see the name of the current conference.To fix the bug, write a condition that handles the equal start and end values. Firstly, change the result value at runtime using the Evaluate and log field of the Breakpoints dialog Ctrl+Shift+F8:
Resume the program execution F9 and choose other conferences from the list. When a conference has the same end and start dates (for example, Mobilization or Mobile Optimized 2019), the execution will stop. On the Watches tab, you will see the correct value of the result variable:
Since the code added at runtime has fixed the issue, you can add it in the editor and rerun Shift+F10 the application:
func textDates() -> String { var result = start.dateToString() if self.end == self.start{ return result } if let end = self.end { result = "\(result) - \(end.dateToString())" } return result }
Set symbolic breakpoints and work with the Disassembly view
Problem
Select the Swift Leeds conference and click the Go to official website link. The linked web page cannot open as the address contains an error.
Solution
Let’s handle such cases with symbolic breakpoints: we will add a breakpoint that will stop the program execution any time a URL is opened in the application.
Go to the Breakpoints dialog Ctrl+Shift+F8, click , and select Symbolic Breakpoint. In the Symbol Name field, type the following:
[UIApplication openURL:options:completionHandler:]Press Shift+F9 to start debugging and open the same link. The program execution will stop at the method specified for the symbolic breakpoint, and you will see the disassembled code of this method in the dedicated view:
Go to the LLDB tab of the Debug tool window and type the following command in the LLDB console:
po $arg3This will return the first parameter of the method the debugger stopped at:
This is an invalid URL passed as a parameter of the
open(_:options:completionHandler:)
method.Go to iOSConferences/Resources/conferencesData.json and correct the misprint:
{ "name": "SwiftLeeds", "link": "http://swiftleeds.co.uk/", "start": "2020-10-07", "end": "2020-10-08", "location": "🇬🇧 Leeds, UK" }
What’s next
To learn more about debugging tools available in AppCode, refer to the Debug code section. The view debugging is not supported in AppCode out-of-the-box, but you can use the Reveal application for this purpose, see more in Debugging iOS Apps with Reveal. If you are used to debugging in Xcode, see our migration guide that points out the general differences between the two IDEs.