Xcode 4 Cookbook

By Steven F. Daniel
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Getting and Installing the iOS SDK Development Tools

About this book

The release of iOS 6 comes packed with over 1,500 new APIs and 200 new features. Xcode 4 Cookbook will teach youhow to integrate iCloud storage and how to go about using the Facebook and OpenGraphi APIs, as well as providing you with practical step-by-step recipes covering User Interfaces, data management, multimedia, localisation services and maps, right through to application deployment to the Apple App Store. You will soon be mastering the technology and the skills needed to create some amazing applications.

"Xcode 4 Cookbook" will help you learn how to build some powerful applications using iOS 6 and the various frameworks. You will soon master how to incorporate iCloud, Facebook, and the OpenGraph APIs and apply various image filters and transitions using Core Image integration within your applications. By using the book’s step-by-step approach, you will soon master the technology and the skills needed to create some amazing applications.

"Xcode 4 Cookbook" provides you with the skills and knowledge and practical recipes on how to go about developing useful applications that can be used within the industry.

You will start by learning how to go about downloading and installing the Xcode Development Tools, learn about Interface Builder to create the visual user interfaces, connecting the objects using Outlets and Actions, and learn how to compile/debug your applications.

Finally, you will learn how to capture media with the iOS camera and play back video content using Airplay to wirelessly stream videos to an Apple TV device, using the AV Foundation framework, as well as using the Core Image and Core Graphics frameworks to create amazing image effects using the built-in features.

Publication date:
May 2013
Publisher
Packt
Pages
402
ISBN
9781849693349

 

Chapter 1. Getting and Installing the iOS SDK Development Tools

In this chapter, we will cover:

  • Downloading and installing the iOS SDK

  • Using Xcode to create an iOS project

  • Using Interface Builder to create the user interface

  • Building the user interface for our application

  • Creating outlets to Interface Builder objects

  • Creating actions that respond to user actions

  • Compiling your project

  • Using the iOS Simulator to test your applications

  • Configuring and using compiler directives

  • Debugging your iOS applications using Xcode

  • Using the Clang Static Analyzer to examine your code

 

Introduction


Welcome to the exciting world of iOS programming using iOS 6. This latest release of the mobile operating system is packed with some great new features and improvements, and comes with over 200 new features as well as an updated SDK featuring over 1,500 new development APIs that can be incorporated into your applications.

In this chapter, we will look at what integrated development environments (IDEs) and software development kits (SDKs) are needed to develop applications for the iOS platform, Apple's operating system for mobile devices. We will explain the importance of each tool's role in the development cycle, before finally developing our first application. The tools that are required to develop applications for the iOS platform are explained, as follows:

  • An Intel-based Mac computer running the Snow Leopard (10.6.*), Lion (10.7.*), or OS X Mountain Lion (10.8.*) operating system: The essential development tools cannot be installed on any other computer platforms, so if you are running another processor type (such as the older Mac G4 or Mac G5), you're out of luck.

  • iOS 5 SDK (or higher): In order to download the Apple iOS SDK, you must be registered as an Apple developer. The iOS SDK consists of the following components:

    Component

    Description

    Xcode

    This is the main IDE that enables you to develop, edit, and debug native applications for the iOS and Mac platforms using the Objective-C programming language.

    iOS Simulator

    This is a Cocoa-based application that enables you to debug your iOS applications on the computer, without the need of having an iOS device. There are many iOS features that simply won't work within the Simulator, so a device is required if an application uses those features, that is, the Core Location and MapKit frameworks.

    Instruments

    These are the analysis tools that help you optimize your applications and monitor for memory leaks during execution of your application at real time.

    Dashcode

    This enables you to develop web-based iOS applications and dashboard widgets.

 

Downloading and installing the iOS SDK


This recipe includes information on how to sign up to the Apple Developer Program, as well as how to download and install the necessary tools needed to develop applications using Xcode.

Getting ready

Before you can start building iOS applications, you must first join up as a registered user of the iOS Developer Program in order to download all of the necessary components to our computer. At the time of writing, the latest version is 4.5.2, and iOS SDK's latest version is 6.x. The registration process is free, and provides you access to the iOS SDK and other developer resources that are really useful for getting you started.

The following short list outlines some of the things that you will be able to access when you become a member of the iOS Developer Program:

  • Helpful getting started guides to help you get up and running quickly

  • Helpful tips that show you how to submit your apps to the App Store

  • Ability to download current releases of the iOS software

  • Ability to beta test releases of iOS and the iOS SDK

  • Access to the Apple Developer Forums

    Note

    Whether you are developing applications for the iPhone or iPad, these use the same operating system (OS) and iOS SDK to allow you to create universal applications that will work with both the iPhone and iPad running on iOS 4.3.* and above.

How to do it...

To prepare your computer for iOS development, you will need to download and install the necessary components in the following order:

  1. To sign up to the iOS Developer Program, you will need to go to https://developer.apple.com/devcenter/ios/index.action and then click on the Log in button to proceed, as shown in the following screenshot:

  2. Once you have signed up, you will then be able to download the iOS SDK and proceed with installing it onto your computer.

  3. Xcode can also be obtained from the Mac App Store at the following link http://itunes.apple.com/us/app/xcode/id497799835?mt=12, depending on whether you have chosen the version for Mac OSX Lion. The installation procedure in the remaining steps shows how to go about installing the iOS development tools for Snow Leopard.

  4. Once you have downloaded the SDK for Snow Leopard, you can proceed with installing it. You will be required to accept a few licensing agreements. Once you have done that, all you need to do is select the destination folder of the installation and click on the Continue button.

  5. If you select the default settings during the installation phase, the various tools will be installed in the /Developer/Applications folder. The installation process takes you through the custom installation options screen, as shown in the following screenshot:

These options give you a little more control over the installation process. For example, you are able to specify the folder location in which you would like to install Xcode, as well as settings for a variety of other options.

How it works...

Now that everything has been installed and is ready to go, our next step is to take a look at what each component within the Xcode and iOS SDK is needed for.

As mentioned in the Introduction section of this chapter, the iOS SDK is made up of three important components. The main component, Xcode IDE, is Apple's IDE that allows for developing applications for the iOS and Mac platforms, and uses Objective-C as the default programming language.

This environment allows for better integration and editing of source code, and building, compiling, and debugging your applications. It contains a number of tools that can help with diagnosing issues with your iOS applications. The topic on instruments, will be covered later on in this book. The IDE contains a device information window, called Organizer – Devices, which is shown in the following screenshot:

This screen is necessary to install the various certificates and provisioning profiles that are required for deploying an application onto a device for testing, or distribution through the Apple App Store. Using the Organizer – Devices window, you can view debugging information of your applications, crash logs, as well as the ability to take screenshots from the device.

  • Interface Builder: This is the user interface designer that is integrated within the IDE. Interface Builder provides you with all the necessary functionality to construct an application's user interface. All of your objects are stored within one or more resource files and contain the associated relationship to each of the objects. Any changes that you make to the form design are automatically synchronized back to your code.

  • iOS Simulator: This is an extremely useful tool that acts as a testbed for your applications without the need for using an actual device, whether an iPad or any other iOS device. Whenever you build and run your application, Xcode installs your application on the iOS Simulator and launches this for you automatically.

    The iOS Simulator has the capability of simulating the different iOS versions, and this can become extremely useful if your application needs to be installed on different iOS platforms, as well as testing and debugging errors reported in your applications when run under the different iOS versions.

There's more…

The following list provides you with the links that contain the tools and information for installing them:

See also

  • The Compiling your project recipe

  • The Debugging your iOS applications using Xcode recipe

  • The Using provisioning profiles to install an iOS app on an iOS device recipe in Chapter 10, Packaging and Deploying Your Application

  • The Submitting an application to the App Store using iTunes Connect recipe in Chapter 10, Packaging and Deploying Your Application

 

Using Xcode to create an iOS project


In this recipe, we will see how easy it is to create our very first iOS application project using the Xcode IDE.

Getting ready

Now that we have all of the preliminary components installed, we will start to create our very first HelloWorld project using Xcode.

How to do it...

To begin with creating a new Xcode project, perform the following simple steps:

  1. Launch Xcode from the /Developer/Applications folder.

  2. Choose Create a new Xcode project, or File | New Project.

  3. Select Single View Application from the list of available templates, as shown in the following screenshot:

  4. Click on the Next button to proceed to the next step in the wizard.

  5. Next, enter HelloWorld as the name of your project.

  6. Select iPhone from under the Devices drop-down menu.

  7. Ensure that the Use Storyboards checkbox has not been checked.

  8. Ensure that the Use Automatic Reference Counting checkbox has been checked.

  9. Ensure that the Include Unit Tests checkbox has not been checked.

    Note

    The Company Identifier for your app needs to be unique. Apple recommends that you use the reverse domain style (for example, com.domainName.appName).

  10. Click on the Next button to proceed to the next step in the wizard.

  11. Specify the location where you would like to save your project.

  12. Then, click on the Create button to save your project at the specified location.

Once your project has been created, you will be presented with the Xcode development environment, along with the project files that the template created for you. If you want, you can build and run the application. The iOS Simulator will start and show a blank white screen.

How it works...

Now that we have created our HelloWorld project, let's take the time to see what the template wizard created for us.

When Xcode creates a new iOS project, it also creates a series of files. Depending on what options have been selected during this process may result in some additional files being created.

The following screenshot shows a list of the essentials files that form part of an iOS project:

The following are the important files to take a note of:

  • main.m

  • AppDelegate.h and AppDelegate.m

  • ViewController.h and ViewController.m

  • HelloWorld-info.plist

main.m

The main function is where the runtime lifecycle of your program starts and ends. The UIApplicationMainstarts function runs the loop that is responsible for sending notifications to the application through the AppDelegate class, and contains the various event handlers that can be overridden. This function takes four parameters and uses them to initialize the application.

//  main.m
//  HelloWorld
//
//  Created by Steven F Daniel on 18/12/11.
//  Copyright (c) 2012GenieSoft Studios. All rights reserved.

#import <UIKit/UIKit.h>
#import "AppDelegate.h"

int main(int argc, char *argv[])
{
  @autoreleasepool {
  returnUIApplicationMain(argc, argv, nil, 
NSStringFromClass([AppDelegate class]));
  }
}

There's more…

You will notice that within our main function, it contains @autoreleasepool, which is an object to support the memory management system for your iOS device. Next, we are including the argc and argv[] parameters. Given that all iOS applications run within a graphical interface and don't run from the command line, these are simply here so that they conform to the standard ANSI C coding practices.

Understanding application delegates

The application delegate implements how your program should react at critical points during the application lifecycle. The delegate is responsible for initializing a window at application startup and cleaning up at program termination. This class is responsible for causing the main view controller to be displayed, as well as handling application responsiveness whenever your application suspends or resumes.

Understanding the ViewController class

This file implements the views functionality and contains the class methods that correspond to the view that is being loaded, as well as the method declarations that can be overridden. In the following table, we describe some of the methods that are contained within this class:

Method name

Description

viewDidLoad

This method is called whenever the view controller is loaded, and is used to set up any additional objects.

viewDidUnload

This method is called whenever the view is unloaded from memory.

viewWillAppear

This method is called whenever the view is ready to appear on the devices' screen, or that it has fully appeared already.

viewDidAppear

This method is called whenever you want to perform a particular action, once the view has fully appeared on screen, such as performing some sort of transition animation or sound.

shouldAutorotateToInterfaceOrientation

This method is normally used whenever you want your application to support multiple screen orientations, that is, landscape or portrait.

Understanding ViewController.xib

The XIB file may not be visible depending on whether you selected to use storyboards during the creation of your project. The XIB file is basically an XML file with a specific structure that is readable from Interface Builder, and contains various information about the user interface, such as the type of controls it contains, their properties, outlets, and so on.

Understanding HelloWorld-info.plist

This file is basically the applications' settings file and contains the properties and their values that define the various settings for an iOS application. These settings have information relating to the device orientations that it will support, the application icon and the supported iOS versions, as well as what devices the application can be installed on. The following screenshot shows the structure of this file when it has been double-clicked in the Xcode editor:

See also

  • The Building the user interface for our application recipe

  • The Creating outlets to Interface Builder objects recipe

  • The Adding and customizing views recipe in Chapter 2, User Interfaces – Creating the UI

 

Using Interface Builder to create the user interface


In this recipe, we will familiarize ourselves with the Interface Builder application. Interface Builder is a visual tool that enables you to design the user interface for your iOS applications.

Using Interface Builder, you are able to drag-and-drop views and objects onto your canvas area from the libraries pane. These objects can then be connected using outlets and actions so that they can programmatically interact with your code.

How to do it…

To display our view controller within Interface Builder and the Xcode environment, perform the following simple steps:

  1. Select the ViewController.xib file from the project navigator window.

  2. From the Xcode toolbar, select the viewing options, as shown in the following screenshot:

In the preceding screenshot, this shows what Interface Builder looks like when an XIB file has been chosen from the project navigator window.

How it works…

Whenever you use Interface Builder to design a user interface, any objects that have been used from the library pane will be connected to the Xcode project that they belong to.

As you can see from the preceding screenshot, the Interface Builder workspace is divided into three main areas. The following table provides a brief description of which area is used for what functions:

Area name

Description

Navigation area

This area displays all files associated with the project.

Editor area

This area is where we start to design our user interface from.

Inspector pane

This area is where we can configure each of our objects.

Library pane

This area is where we can locate objects and drag them onto our view. Such objects are the UILabel, UIButton, UITextField, and so on.

There's more…

You may have noticed the section called Simulated Metrics located on the Attributes tab within the inspector pane window. This area shows you how our interface will look like within the designer, and eventually how it will look like when it is deployed and run on the iOS device.

Here you can specify whether your interface will have a status bar, toolbar, or even a navigation bar. It is worth mentioning that, if you set the Status Bar option to None, it does not mean that our application will start without a status bar.

Note

The status bar is the bar that appears at the top of the device's screen and displays certain types of information to the user, such as the current time, battery status, carrier name, and so forth.

See also

  • The Building the user interface for our application recipe

  • The Creating outlets to Interface Builder objects recipe

  • The Adding and customizing views recipe in Chapter 2, User Interfaces – Creating the UI

 

Building the user interface for our application


In this recipe, we will learn how to go about building our user interface and how to add controls.

Getting ready

Now that we have successfully created our project, we can start building our user interface using the Interface Builder designer.

How to do it…

Creating the user interface for our application using Interface Builder is really easy, and can be achieved by performing the following simple steps:

  1. Select ViewController.xib from the project navigator window.

  2. From Object Library, drag a (Label) control to the view's canvas.

  3. Then, from the Attributes Inspector section, modify the Text property to read Firstname:.

  4. Next, resize the Label control so that the contents of the label fit.

  5. Then, from Object Library, drag a (Textfield) control to the view and place it to the right-hand side of the Firstname label and resize the Textfield control so that it is wide enough to fit the field contents.

  6. From Object Library, drag a (Label) control to the view's canvas.

  7. From the Attributes Inspector section, modify the Text property to read Surname:.

  8. Next, resize the Label control so that the contents of the label fit.

  9. Then, from Object Library, drag a (Textfield) control to the view and place it to the right-hand side of the Surname label and resize the Textfield control so that it is wide enough to fit the field contents.

  10. From Object Library, drag a (Label) control to the view's canvas and place it a bit further down under the Surname label.

  11. From the Attributes Inspector section, modify the Text property to read Output:.

  12. Next, resize the Label control to about the width of the screen.

  13. Then, from Object Library, drag a (Button) control to the view and place it underneath the Label control and centered.

  14. Resize the Button control so that it is wide enough to fit the field contents.

  15. From the Attributes Inspector section, modify the Title property to read Tap Here.

  16. After adding the button, save the document by selecting File | Save from the menu bar. The main view should now look like the following screenshot:

How it works…

As you can see, using Interface Builder is not difficult once you get used to it. Whenever you drag objects onto your view, you will notice that a small green circled cross appears on the cursor to indicate that it is safe to drop the object onto the view.

From this view, we are also able to resize the control, as well as modify the attributes associated with the control.

See also

  • The Building the user interface for our application recipe

  • The Creating outlets to Interface Builder objects recipe

  • The Creating actions that respond to user actions recipe

 

Creating outlets to Interface Builder objects


In this recipe, we will take a closer look at outlets and how these can be used to communicate with our UI.

Getting ready

In our previous section, we looked at how to add controls to our ViewController to form the construction of our user interface as well as set some properties to our controls. In this section, we will look at how we can connect these up and access these controls within our code.

How to do it…

Creating outlets to Interface Builder objects is a simple process and can be achieved by performing the following simple steps:

  1. Open the assistant editor by selecting Navigate | Open In Assistant Editor or pressing option + command + ,.

  2. Ensure that the ViewController.h interface file is displayed within the assistant editor window.

  3. Next, select the Firstname (Label) control, then hold down the command key and drag it into the ViewController.h interface file, within the brackets and the @interface and @end lines.

  4. Choose Outlet from the Connection drop-down menu for the type of connection to create.

  5. Enter lblFirstname for the name of the outlet property to create.

  6. Choose Strong from the Storage drop-down menu and click on the Connect button.

  7. Next, select the Firstname (Textfield) control, then hold down the command key, and drag it into the ViewController.h interface file.

  8. Choose Outlet from the Connection drop-down menu for the type of connection to create.

  9. Enter in txtFirstname for the name of the Outlet property to create.

  10. Choose Strong from the Storage drop-down menu and click on the Connect button.

  11. Repeat steps 3 to 9 to add the Surname, Label, and Tap Here button, while providing the names such as lblSurname, txtSurname, lblOutput, and btnTapHere for each.

    Note

    Whenever you create an outlet, these will need to be created within the curly braces { }. The Interface Builder designer does not create these for you automatically, so you will need to add these before you create your outlets.

  12. Once you have created the necessary outlets, it would be good to save your project by selecting File | Save, or alternatively pressing Command + S.

How it works…

Whenever we use outlets, these simply provide a means of allowing our Interface Builder objects to communicate with the code. This is necessary and is the only way in which we can access the user interface objects that have been created within the Interface Builder designer environment.

There's more…

There is another thing that we need to do when declaring outlets and that is to create the necessary properties for them. Creating these properties provides us access to these controls, and automatically creates the getter and setter methods for our objects.

Creating properties to Interface Builder objects is a similar process to adding outlets, and can be achieved by performing the following simple steps:

  1. Ensure that the ViewController.h interface file is displayed within the assistant editor window.

  2. Next, select the Firstname (Label) control, then hold down the command key and drag it into the ViewController.h interface file at the end of the closing curly brace.

  3. Choose Outlet from the Connection drop-down menu for the type of connection to create.

  4. Enter lblFirstname for the name of the outlet property to create.

  5. Choose Strong from the Storage drop-down menu and click on the Connect button.

  6. Next, select the Firstname (Textfield) control, then hold down the command key, and drag it into the ViewController.h interface file.

  7. Choose Outlet from the Connection drop-down menu for the type of connection to create.

  8. Enter txtFirstname for the name of the outlet property to create.

  9. Choose Strong from the Storage drop-down menu and click on the Connect button.

  10. Repeat steps 3 to 9 to add the Surname, Label, and Tap Here button, while providing the names such as lblSurname, txtSurname, lblOutput, and btnTapHere for each.

Once you have created each of the property outlets, the completed ViewController.h interface file will resemble the following code snippet:

//  ViewController.h
//  HelloWorld
//
//  Created by Steven F Daniel on 22/08/12.
//  Copyright (c) 2012 GenieSoft Studios. All rights reserved.

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    IBOutlet UILabel        *lblFirstname;
    IBOutlet UITextField  *txtFirstname;
    IBOutlet UILabel        *lblSurname;
    IBOutlet UITextField  *txtSurname;
    IBOutlet UILabel        *lblOutput;
    IBOutlet UIButton      *btnTapHere;
}

@property (strong, nonatomic) IBOutlet UILabel *lblFirstname;
@property (strong, nonatomic) IBOutlet UITextField *txtFirstname;
@property (strong, nonatomic) IBOutlet UILabel *lblSurname;
@property (strong, nonatomic) IBOutlet UITextField *txtSurname;
@property (strong, nonatomic) IBOutlet UILabel *lblOutput;
@property (strong, nonatomic) IBOutlet UIButton *btnTapHere;

@end

Since we created our outlets, you will notice that Interface Builder has also created each of our outlets and have declared these within our ViewController.m implementation file, as shown in the following code snippet:

//  ViewController.m
//  HelloWorld
//
//  Created by Steven F Daniel on 22/08/12.
//  Copyright (c) 2012 GenieSoft Studios. All rights reserved.

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize lblFirstname;
@synthesize txtFirstname;
@synthesize lblSurname;
@synthesize txtSurname;
@synthesize lblOutput;
@synthesize btnTapHere;

See also

  • The Using Interface Builder to create the user interface recipe

  • The Building the user interface for our application recipe

  • The Creating actions that respond to user actions recipe

 

Creating actions that respond to user actions


In this recipe, we will take a closer look at actions and how these can be used to respond to user actions.

Getting ready

In our previous section, we looked at how to add controls to our ViewController to construct our user interface and connect up each of the outlets, as well as create properties for each of our controls. In this section, we will look at how we can communicate with these outlets and display a message to the user when the Tap Here button is clicked.

How to do it…

Adding actions to interface objects is a process similar to adding outlets, and can be achieved by performing the following simple steps:

  1. Open the assistant editor by selecting Navigate | Open In Assistant Editor or by pressing option + command + ,.

  2. Ensure that the ViewController.h interface file is displayed within the assistant editor window.

  3. Next, select the Tap Here (Button) control, then hold down the command key, and drag it into the ViewController.h interface file.

  4. Choose Action from the Connection drop-down menu for the type of connection to create.

  5. Enter btnTapHere for the name of the action to create and click on the Connect button.

How it works…

Whenever actions are created in Objective-C, they are responsible for responding and executing the associated code behind it. Instead of us hooking up an event handler to the TouchUpInside event of the button, we have decided to add an action to it and handle the output of this ourselves. These types of actions are called instance methods.

There's more…

Our next step is to add the code into our btnTapHere event method, which will display a greeting message to the user when this button is clicked. Perform the following steps to do so:

  1. Open the ViewController.m implementation file from the project navigator.

  2. Next, locate the btnTapHere event method and enter the following code snippet:

    - (IBAction)btnTapHere:(id)sender { 
        NSString *greeting = [NSStringstringWithFormat:@"Welcome 
                      To Xcode 4 Cookbook series %@ %@",txtFirstname.text, txtSurname.text];    
        lblOutput.text = greeting; 
        lblOutput.font = [UIFont boldSystemFontOfSize:21]; 
        lblOutput.textColor = [UIColorblueColor]; 
    }

In our code snippet, we create an NSString object value called greeting, and then use the stringWithFormat method to concatenate our firstname and surname objects. Next, we assign this variable to our output label and then apply the font size and text color.

See also

  • The Compiling your project recipe

  • The Debugging your iOS applications using Xcode recipe

  • The Using the iOS Simulator to test your applications recipe

 

Compiling your project


In this recipe, we will take a look at how we can compile our project with Xcode.

Getting ready

Xcode offers various options for compiling your application. In this section, we will take a look at these options.

How to do it…

Whenever you want to compile your application, you have the option of choosing to have your application run on the iOS device, or within each of the simulators for iPad or iPhone. The version number associated with the Simulators is dependent on the version of the iOS SDK you have installed on your computer. In Xcode 4, whenever you open an existing Xcode project or create a new one, Xcode will automatically create a default scheme for you.

This scheme allows you to either test your application within the iOS Simulator, or have it deployed to an iOS device. Additional schemes can be created, which we will shortly take a look at.

Schemes are not new to Xcode 4 and they have existed since the early releases of Xcode 3. In previous releases of Xcode, you had to configure each of the items separately when setting an active target, a build configuration, or even an executable.

This posed many issues as all of these were linked to each other. This is where defining your own schemes comes in.

Schemes can be thought of as separate configurations, meaning that you can create a scheme to specify which targets to build, what configuration build to use, and what executable environment to use when the product specified by the target is launched (this could be if you wanted to target a specific iOS version, or if you wanted to have the application launch within the iOS Simulator). Perform the following steps:

  1. To choose a scheme, you can just select it from the scheme pop-up menu, as shown in the preceding screenshot. HelloWorld is our default scheme that was created for us automatically when the project was created.

  2. In order to create a new scheme, select the New Scheme… option. Alternatively, if you wanted to edit the active scheme you can choose the Edit Scheme… option. These options are also available under the Product menu.

    Each scheme can be set to do a specific task. For instance, you may have a scheme to do a design build and one to handle the release or distribution. Various types of build options are available for building, testing, running, profiling (using instruments), and archiving your products, which can then be submitted to the App Store. There is no limit on the number of schemes that you can define. However, only one scheme can be active at one time.

  3. Schemes can also be managed by selecting the Manage Schemes… option, or similarly from the Product menu.

You can specify whether schemes should be stored on a per-project basis, in which case these will be made available to every workspace that includes that project, or you can choose to have it stored within the workspace environment that it's currently in.

The following screenshot shows how you can customize the active scheme. You can specify the type of build configuration to use, the type of debugger, and the current working directory to use. You can also choose to have your product run at a higher resolution, which enables you to simulate your application running at different display resolutions.

 

Using the iOS Simulator to test your applications


In this recipe, we will take a look at how we can run our HelloWorld application using the iOS Simulator.

Getting ready

Now, let's run our application using the iOS Simulator. With the project window opened, ensure that you have selected the active scheme configuration to HelloWorld | iPhone Simulator.

How to do it…

Next, build and run the application by selecting Product | Run from the Product menu, or alternatively by pressing command + R.

When the compilation completes, the iOS Simulator will appear automatically and your application that we just created will be displayed. Fill in the text fields and then click on the Tap Here button to see your result.

How it works…

The iOS Simulator is a fantastic tool that enables developers to test their applications without the need for an actual device. Whenever you use the iOS Simulator to build and run your application within the Xcode IDE, Xcode automatically installs your application within the iOS Simulator for you.

One of the other nice features of the iOS Simulator is that it has the capability of simulating different iOS versions, and this can be extremely useful if your application needs to be installed on different iOS platforms, as well as testing and debugging errors reported in your application when run under the different iOS versions.

It is worth mentioning that testing on the iOS Simulator is only good for a first round of testing, since it's not even running iOS code and it's more forgiving than the real device (for example filenames are case insensitive typically (Mac filesystem rules)), you can write files anywhere. Testing on a Simulator is never a substitute for testing on a device.

In the end, you're just running your application in a Mac OS X application running on an Intel processor. It's not even close to running under iOS on a device. It's useful for catching obvious errors or doing quick testing during development, but you still need to device test.

See also

  • The Compiling your project recipe

  • The Debugging your iOS applications using Xcode recipe

  • The Registering your iOS devices for testing recipe in Chapter 10, Packaging and Deploying Your Application

  • The Creating the development provisioning profiles recipe in Chapter 10, Packaging and Deploying Your Application

  • The Using the provisioning profile to install the app on an iOS device recipe in Chapter 10, Packaging and Deploying Your Application

 

Configuring and using compiler directives


In C/C++, we use directives to include any other header files that our application will need to access. This is done by using the #include directive. In Objective-C, we use the #import directive. If you examine the contents of the ViewController.h file, you will notice that at the top of the file is a #import statement.

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    IBOutlet UILabel     *lblFirstname;
    IBOutlet UITextField *txtFirstname;
    IBOutlet UILabel     *lblSurname;
    IBOutlet UITextField *txtSurname;
    IBOutlet UILabel     *lblOutput;
    IBOutlet UIButton    *btnTapHere;
}

The #import statement is known as a preprocessor directive. As mentioned previously, in C/C++, you would use the #include preprocessor directive to include a file's content within the current source file. In Objective-C, you would use the #import directive statement to achieve the same result, with the exception that the compiler ensures that the file is only included once.

To import a header file from one of the Xcode framework libraries, you would specify the header filename using the angle brackets (<>) within the #import statement.

If you wanted to import one of your own custom-built header files containing your own methods, you would specify and make use of the double-quoted marks (""), as you can see from the following sample code:

#import <UIKit/UIKit.h>
#import "MyClass.h" 

@interface ViewController : UIViewController {
}

In this recipe, we will be taking a look at another approach where we can use directives to conditionally compile code based on a conditionally set pre-compiler flag that you can define yourself. This makes it easy for you to selectively enable parts of your application without making your code look messy.

Getting ready

In HelloWorld-Prefix.pch, we will start by declaring a few macros (so you don't have to litter your code with #ifdef/#endif blocks). The HelloWorld-Prefix.pch file is global in scope, so any functions you define there will be available in all of your classes, so this can be very useful.

How to do it...

Declaring compiler directives for your application is a very simple process, and can be achieved by performing the following simple steps:

  1. Open the HelloWorld-Prefix.pch implementation file from the project navigator, located under the supporting files group.

  2. Next, enter the following highlighted code snippet to this file:

    //
    // Prefix header for all source files of the 'HelloWorld' target in the 'HelloWorld' project
    //
    
    #import <Availability.h>
    
    #ifndef __IPHONE_4_0
    #warning "This project uses features only available in iOS SDK 4.0 and later."
    #endif
    
    #ifdef __OBJC__
        #import <UIKit/UIKit.h>
        #import <Foundation/Foundation.h>
    #endif
    
    #ifdef DISPLAY_FIRSTNAME
    #warning "This application will display the value of the First namefield."
    #else
    #warning "This application will display the values of both the First name and Surname fields."
    #endif
    
  3. Next, we need to modify our btnTapHere method to be surrounded by an #ifdef statement, within our ViewController.m implementation file, as follows:

    - (IBAction)btnTapHere:(id)sender { 
    #ifdef DISPLAY_FIRSTNAME 
          NSLog(@"Using the Firstname field."); 
          NSString *greeting = [NSString stringWithFormat:@"Welcome to Xcode 4 Cookbook series  %@",txtFirstname.text];
    #else
        NSLog(@"Using Firstname and Surname  fields."); 
         NSString *greeting = [NSString  stringWithFormat:@"Welcome to Xcode 4 Cookbook series %@ %@",txtFirstname.text, txtSurname.text]; 
    #endif 
    
    lblOutput.text = greeting;
    lblOutput.font = [UIFont boldSystemFontOfSize:21];
    lblOutput.textColor = [UIColorblueColor];
    }

Whenever you want to display just the first name of the user, you simply set this to YES by defining the conditional flag.

How it works…

Whenever compiler directives are used in Objective-C, they are responsible for responding to and executing the associated snippets of code encapsulated within the #ifdef and #endif tags.

This is particularly handy if you only want to force a set of NSLog messages or values to be used during testing, and not appear during the final release of your application. Some other uses where these types can be used would be, if you were creating a game and you wanted to disable some features in the trial or lite version of your game.

There's more…

In order to have your application use this compiler directive, we need to add this preprocessing flag to the Preprocessor Macros section, as follows:

  1. Select the HelloWorld project from the project navigator window.

  2. Next, select the HelloWorld project and then click on the Build Settings tab.

  3. Then, scroll down to the Apple LLVM compiler 4.0 – Preprocessing section.

  4. Double-click on the Debug section and then add the DISPLAY_FIRSTNAME=YES preprocessor flag.

  5. Dismiss this window by clicking outside within the project window.

    That's all there is to it, easy. If you want to turn DISPLAY_FIRSTNAME off (for example, when you're ready to do your final release build), simply head back to this section and remove the flag from your project preferences.

  6. Next, build and run the application by selecting Product | Run from the Product menu, or alternatively by pressing command + R and entering values for both Firstname and Surname. You should see a welcome message showing only your first name.

See also

  • The Compiling your project recipe

  • The Debugging your iOS applications using Xcode recipe

  • The Using the iOS Simulator to test your applications recipe

 

Debugging your iOS applications using Xcode


In this recipe, we will show how easy it is to debug applications within Xcode and the iOS Simulator.

Getting ready

Xcode 4, provides you with a debugger for debugging your applications either using the iOS Simulator or on the actual iOS device. In this recipe, we will see how easy it is to debug applications to debug our HelloWorld application.

How to do it…

Debugging your application using the Xcode development environment is a simple process, and allows you to monitor changes to your application variables, as well as stepping through your source code line by line, and can be achieved by performing the following simple steps:

  1. Open the ViewController.m implementation file from the project navigator.

  2. Next, locate the btnTapHere event method and place a breakpoint within the gray gutter, as shown in the following screenshot.

  3. You will notice that an arrow appears at the line you placed the marker at.

  4. Next, build and run the application by selecting Product | Run from the Product menu, or alternatively by pressing command + R.

  5. Populate the Firstname and Surname fields, and click on the Tap Here button.

  6. You will notice that execution of our application has paused, and the debugger has stopped at the line where we placed our breakpoint.

  7. Hover the mouse over the greeting variable in the breakpoint line to see the contents of the greeting label.

  8. To continue execution of your application, click on the Continue program execution button.

How it works…

Although you can use the debugger to pause execution of your program at any time and view the state of your program variables, it is better to set the breakpoints before you run your application.

A breakpoint is basically an instruction that tells the application to stop when the breakpoint has been reached. During this phase, the execution of your code pauses and waits for further instructions as to what to do next. During this phase, you have the opportunity to either inspect the current values of any of the properties, or step through the code.

See Also

 

Using the Clang Static Analyzer to examine your code


In this section, we will take a look at how we can use the Clang Static Analyzer tool to examine the syntax of our code for bugs.

Getting ready

There may be times when you want to examine the syntax of your code for bugs. This is where the Static Analyzer tool comes handy. This tool was first introduced back in Xcode 3.x, and opened and displayed the build results in a new window.

Xcode 4 allows you to perform the analysis of your code, examine the results, and apply the fixes to your source files all within the Xcode 4 workspace environment.

How to do it…

To run the Static Analyzer, perform the following simple steps:

  1. Select the HelloWorld project from the project navigator window.

  2. Open the ViewController.m implementation file.

  3. Locate the btnTapHere method and enter the following modified code snippet:

    - (IBAction)btnTapHere:(id)sender {
     UIColor *color;
     int colorIndex;
    
    #ifdef DISPLAY_FIRSTNAME
          NSLog(@"Using the Firstname field.");
          NSString *greeting = [NSString stringWithFormat:
    @"Welcome to Xcode 4 Cookbook series %@",
    txtFirstname.text];
    #else
          NSLog(@"Using Firstname and Surname fields.");
          NSString *greeting = [NSString stringWithFormat:
    @"Welcome to Xcode 4 Cookbook series %@ %@",
    txtFirstname.text, txtSurname.text];
     #endif
    
    if (colorIndex == 1) {
          lblOutput.textColor = [UIColor redColor];
    }
    else if (colorIndex == 2) {
          lblOutput.textColor = [UIColor blueColor];        
    }
    else if (colorIndex == 2) {
          lblOutput.textColor = [UIColor purpleColor];
    }
    else {
          lblOutput.textColor = [UIColor blueColor];
        }
    
          lblOutput.text = greeting;
          lblOutput.font = [UIFont boldSystemFontOfSize:21];
    }
  4. Select Product | Analyze from the Product menu, or alternatively press down the Shift + command + B key combinations.

How it works…

When the analyzer finishes checking your code for problems, the issues navigator opens automatically and shows you a list of issues that were found within your project. This is shown in the following screenshot:

Clicking on an issue within the left-hand pane will open the file in question, and display the problem that has been marked with a blue triangle. Clicking on this triangle will display the faulty flow of logic that has been identified and detected by the static analyzer, as can be seen in the preceding screenshot.

The static analyzer has flagged that the colorIndex variable has a potential error. This is due to the fact that the variable was not initialized upon declaration and contains some random value.

You will also notice that the analyzer provides additional detail when you click on the message bubbles, and displays the control flow, as can be seen by the arrows. This provides you with a full diagnosis of the bug. Many of the issues that are reported by the static analyzer tool have this information and make the analysis and fixing of these errors much easier.

Note

If you would like to find out more information about the Static Analyzer, you can refer to the Apple developer documentation located at http://developer.apple.com/library/ios/#recipes/xcode_help-source_editor/Analyze/Analyze.html.

See also

  • The Compiling your project recipe

  • The Debugging your iOS applications using Xcode recipe

  • The Using the iOS Simulator to test your applications recipe

  • The Registering your iOS devices for testing recipe in Chapter 10, Packaging and Deploying Your Application

  • The Creating the development provisioning profiles recipe in Chapter 10, Packaging and Deploying Your Application

  • The Using the provisioning profile to install the app on an iOS device recipe in Chapter 10, Packaging and Deploying Your Application

About the Author

  • Steven F. Daniel

    Steven F. Daniel is the CEO and founder of GENIESOFT STUDIOS, a software development company based in Melbourne, Victoria, that focuses primarily on developing games and business applications for the iOS, Android, and Mac OS X platforms.

    He is an experienced software engineer with more than 17 years' experience and is extremely passionate about making people employable by helping them use their existing skills in iOS, Android, and Xamarin to get the job done. He is a member of the SQL Server Special Interest Group (SQLSIG), CocoaHeads, and the Java Community. He was the co-founder and Chief Technology Officer (CTO) at SoftMpire Pty Ltd., a company focused primarily on developing business applications for the iOS and Android platforms.

    Browse publications by this author
Book Title
Access this book, plus 7,500 other titles for FREE
Start FREE trial