9
Debugging

As you write an application, you will inevitably make mistakes. Even worse, from time to time you will have errors in your application’s design. Xcode’s debugger (called LLDB) is the fundamental tool that will help you find these bugs and fix them. This chapter gives you an overview of Xcode’s debugger and its basic functions.

A Buggy Project

You will use a simple project to guide you through your exploration of the Xcode debugger. Open Xcode and create a new project for an iOS single view application. Name the project Buggy and make sure Language is set to Swift, Devices is set to iPhone, and Use Core Data, Include Unit Tests, and Include UI Tests are all unchecked (Figure 9.1). Click Next.

Figure 9.1  Configuring Buggy

Screenshot of the Xcode IDE “Choose options for your new project” dialog.

As you write this application’s code, keep in mind that it is a buggy project. You may be asked to type code you know is incorrect. Do not fix it as you type it in; those errors will help you learn about debugging techniques.

To get started, open Main.storyboard and drag a UIButton onto the View Controller Scene. Double-click on the new button and change its title to Tap me! With the button still selected, open the Auto Layout Align menu. Check Horizontally in Container and click Add 1 Constraint. Next, open the Add New Constraints menu. Pin the distance to the top of the container, check the Width and Height boxes, and click Add 3 Constraints.

Your results should look something like Figure 9.2, but do not worry if your actual dimensions and spacing are a bit different.

Figure 9.2  Auto Layout constraints for the Tap me! button

Screenshot of the Buggy project’s Canvas with the “tap me!” UI button and its Auto Layout Constraints pane.

Now you need to implement a method for this button to trigger and then connect it to the button in the storyboard.

Open ViewController.swift and implement an action method for the button to trigger.

@IBAction func buttonTapped(_ sender: UIButton) {

}

Now open Main.storyboard and Control-drag from the button to the View Controller and connect it to the buttonTapped: option.

Back in ViewController.swift, add a print() statement to the buttonTapped(_:) method to confirm that the method is called in response to a button tap.

@IBAction func buttonTapped(_ sender: UIButton) {
    print("Called buttonTapped(_:)")
}

Build and run the application. Make sure the button is correctly displayed on the screen and that you can tap it. Also confirm that the Called buttonTapped(_:) message prints to the console when you tap the button.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset