Introduction to Xcode Simulator

9/14/2010 4:51:42 PM

The core of your work in the Apple Developer Suite will be spent in three applications: Xcode, Interface Builder, and the iPhone Simulator. This trio of apps provides all the tools that you need to design, program, and test applications for the iPhone. And, unlike other platforms, the Apple Developer Suite is entirely free!

This hour walks you through the basics you need to work within two of the three components—Xcode and the iPhone Simulator—and you’ll get some hands-on practice working with each.

Using Xcode

When you think of coding—actually typing the statements that will make your iPhone meet Apple’s “magical” mantra—think Xcode. Xcode is the IDE, or integrated development environment, that manages your application’s resources and lets you edit the code that ties the different pieces together.

After you install the developer tools, as described in Hour 1, “Preparing Your System and iPhone for Development,” you should be able to find Xcode in the Developer/Applications folder located at the root level of your hard drive. We walk through the day-to-day use of Xcode in this hour, so if you haven’t installed the tools yet, do so now!

Launch Xcode from the Developer/Applications folder. After a few moments, the Welcome to Xcode screen will display, as shown in Figure 1.

Figure 1. Explore Apple’s developer resources, right from the Xcode Welcome screen.

You can choose to disable this screen by unchecking the Show This Window When Xcode Launches check box, but it does provide a convenient “jumping-off” point for sample code, tutorials, and documentation.Click Cancel to exit the Welcome screen.

Creating and Managing Projects

Most of your iPhone work will start with an Xcode project. A project is a collection of all the files associated with an application, along with the settings needed to “build” a working piece of software from the files. This includes images, source code, and a file that describes the appearance and objects that make up the interface.

Choosing a Project Type

To create a new project, choose File, New Project (Shift+Command+N) from the Xcode menu. Do this now. Xcode will prompt you to choose a template for your application, as shown in Figure 2. The Xcode templates contain the files you need to quickly start on a new development effort. Although it is possible to build an application completely from scratch, the time saved by using a template is pretty significant. We’ll use several templates throughout the book, depending on what type of application we’re building.

Figure 2. To create a new project, start by choosing an appropriate template.

Along the left side of the Template window are the categories of templates you can choose from. Our focus will be on the iOS Application category, so be sure that it is selected.

On the right side of the display are the templates within the category, with a description of the currently highlighted template. For this tutorial, click the Window-Based Application template. Be sure that the product selected is the iPhone (rather than iPad, or Universal, which runs on the iPad and iPhone), and then click the Choose button.

After choosing the template, you’ll be prompted for a location and a name to use when saving the project. Name the test project for this hour HelloXcode and click Save. Xcode will automatically create a folder with the name of the project and place all the associated files within that folder.

Did You Know?

Within your project folder, you’ll find a file with the extension .xcodeproj. This is the file you need to open to return to your project workspace after exiting Xcode.

Project Groups

After you’ve created or opened a project in Xcode, the interface displays an iTunes-like window for navigating the project’s files. On the left side of the window, the Groups & Files list contains a logical grouping of the files within your project. Clicking the top group, called the “project group” (and named after the project), updates the list to the right and shows all the files associated with the application, as shown in Figure 3.

Figure 3. Use the Groups & Files list to navigate through your project resources.

Groups & Files

Group contents

By the Way

Keep in mind that these are logical groupings. You won’t find all these files in your project directory, nor will you find the same folder structure. The Xcode layout is designed to help you find what you’re looking for easily—not to mirror a file system structure.

Within the project group are five subgroups that you may find useful:

Classes: As you’ll learn in the next hour, classes group together application features that complement one another. Most of your development will be within a class file.

Other Sources: These are any other source code files associated with the application. You’ll rarely need to touch these files.

Resources: The Resources group contains the files that define the user interface, application properties, and any images, sounds, or other media files that you want to make use of within the project.

Frameworks: Frameworks are the core code libraries that give your application a certain level of functionality. By default, Xcode includes the basic frameworks for you, but if you want to add special features, such as sound or vibration, you may need an additional framework.

Products: Anything produced by Xcode is included here (typically, the executable application).

Outside of the project group are additional groups, most of which you won’t need to touch for the purposes of learning iPhone development—but a few can come in handy. The Find Results group, for example, contains all the searches you execute, and the files that match. The Bookmarks group enables you to mark specific lines in your code and quickly jump to them. Finally, two smart groups (denoted by the violet folder with the gear icon) are defined by default: Implementation Files and NIB Files. Smart groups cluster together files of a particular type from throughout a project. These groups, in particular, provide quick access to the files where you’ll be adding your application logic (known as implementation files), and the files which define your interface (NIB, “now known as XIB,” files).

By the Way: Didn’t You Just Say My Work Would Be with the Class Files? What’s This About Implementation Files?

As you’ll learn in the next hour, classes are made up of two files: a header, or interface file (ending in .h) that describes the features a class will provide; and an implementation file that actually contains the logic that makes those features work (with a .m suffix). The term implementation file just refers to one of the two files in a class.

Did You Know?

If you find that you want additional logical groupings of files, you can define your own smart groups via Project, New Smart Group.

Adding New Code Files to a Project

Even though the Apple iPhone templates do give you a great starting point for your development, you’ll find, especially in more advanced projects, that you need to add additional code classes or interface files to supplement the base project. To add a new file to a project, choose File, New. In an interface similar to the project templates, Xcode will prompt you, as shown in Figure 4, for the category and type of file that you want to add to the project. You are fully guided throughout this book, so don’t worry if the options in the figure look alien at the moment.

Figure 4. Use Xcode to add new files to a project.

Did You Know?: Can I Add Empty Files Manually?

Yes, you could drag your own files into one of the Xcode group folders and copy them into the project. However, just as a project template gives you a head start on implementation, Xcode’s file templates do the same thing. They often include an outline for the different features that you’ll need to implement to make the code functional.

Adding Resources to a Project

Many applications will require sound or image files that you’ll be integrating into your development. Obviously, Xcode can’t help you “create” these files, so you’ll have to add them by hand. To do this, just click and drag the file from its location into the Resources group in Xcode. You will be prompted to copy the files. Always make sure the “copy” check box is selected so that Xcode can put the files where they need to go within your project directory.

In the downloadable project folder that corresponds with what you’re building this hour, an Images folder contains files named Icon.png and Icon@2x.png. Drag these files from the Finder into to the Xcode Resources folder. Choose to copy if needed, as shown in Figure 2.5. Copying the files ensures that they are correctly placed within your project and accessible by your code.

Figure 5. Drag the Icon.png files into the Resources folder and choose to copy if needed.

These files will ultimately serve as the icon for the HelloXcode app. The reason for two files? The @2x is the icon for an iOS device with a scaling factor of 2 (that is, the double the horizontal and vertical resolution)—in other words, the iPhone 4!

Removing Files and Resources

If you’ve added something to Xcode that you decide you don’t want, you can delete it easily. To remove a file or resource from your project, simply select it within one of the Xcode groups where it appears, and then press the Delete key. Xcode gives you the option to delete any references to the file from the project and move the file to the trash or just to delete the references (see Figure 6).

Figure 6. Deleting a file’s references leaves the actual file untouched.

If you choose to delete references, the file itself will remain, but will no longer be visible in the project.

By the Way

If Xcode can’t find a file that it expects to be part of a project, that file will be highlighted in red in the Xcode interface. This might happen if you accidentally delete a file from the project folder within the Finder. It also occurs when Xcode knows that an application file will be created by a project, but the application hasn’t been generated yet. In this case, you can safely ignore the red .app file within the Xcode groups.

Editing and Navigating Code

To edit code in Xcode, just click the group that contains the file, and then click the filename. The editable contents of the file are shown in the lower-right pane of the Xcode interface (see Figure 7).

Figure 7. Choose the group, then the file, and then edit!

Selected file


The Xcode editor works just like any text editor, with a few nice additions. To get a feel for how it works, click the Classes group within the HelloXcode project, then HelloXcodeAppDelegate.m to begin editing the source code.

For this project, we’re going to use an interface element called a label to display the text Hello Xcode on the iPhone screen. This application, like most that you write, will use a method to show our greeting. A method is just a block of code that executes when something needs to happen. In this sample, we’ll use an existing method called application:didFinishLaunchingWithOptions that runs as soon as the iPhone application starts.

Jumping to Methods with the Symbol Menu

The easiest way to find a method or property within a source code file is to use the symbol pop-up menu, located above the editing pane. This menu, shown in Figure 8, automatically shows all the methods and properties available in the current file and enables you to jump between them by selecting them.

Figure 8. The symbol pop-up menu is a quick way to jump between methods and properties.

Find and select application:didFinishLaunchingWithOptions from the pop-up menu. Xcode will select the line where the method begins. Click the next line, and let’s start coding!

Code Completion

Using the Xcode editor, type the following text to implement the application:didFinishLaunchingWithOptions method. You should need to enter only the bolded code lines, as shown in Listing 1.

Listing 1.
- (BOOL)application:(UIApplication *) application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

// Override point for customization after application launch
UILabel *myMessage;
UILabel *myUnusedMessage;
myMessage=[[UILabel alloc] initWithFrame:CGRectMake((25.0,225.0,300.0,50.0,50.0)];
myMessage.text=@"Hello Xcode";
myMessage.font=[UIFont systemFontOfSize:48];
[window addSubview:myMessage];
[myMessage release];
[window makeKeyAndVisible];

return YES;

Watch Out

If you decide to skip ahead and run this application, you’ll quickly realize that the code you entered is not going to work! Some errors have been intentionally included here that you’ll correct later this hour!

As you type, you should notice something interesting happening. As soon as you get to a point in each line where Xcode thinks it knows what you intend to type, it displays an autocompleted version of the code, as demonstrated in Figure 9.

Figure 9. Xcode automatically completes the code as you type.

Code Completion

To accept an autocompletion suggestion, just press Tab, and the code will be inserted, just as if you typed the whole thing. Xcode will try to complete method names, variables that you’ve defined, and anything else related to the project that it might recognize.

After you’ve made your changes, you can save the file by choosing File, Save.

By the Way

It’s not important to understand exactly what this code does—at this point, you just need to get experience in the Xcode editor. The “short and sweet” description of this fragment, however, is that it creates a label object roughly in the center of the iPhone screen; sets the label’s text, font, and size; and then adds it to the application’s window.

Using Snapshots

If you’re planning to make many changes to your code and you’re not quite sure you’ll like the outcome, you might want to take advantage of the “snapshot” feature. A code snapshot is, in essence, a copy of all your source code at a particular moment in time. If you don’t like changes you’ve made, you can revert to an earlier snapshot. Snapshots are also helpful because they show what has changed between multiple versions of an application.

To take a snapshot, choose File, Make Snapshot. That’s all there is to it!

To view the available snapshots, choose File, Snapshots. The snapshot viewer displays available snapshots. Clicking Show Files displays a list of changed files to the right, and, if a file is selected, the changes that were made between the selected snapshot and the preceding one. Figure 10 shows all of these elements.

Figure 10. Use a snapshot to figure out what changes you’ve made between different versions of your application.

To restore to a specific snapshot, select it in the list, and then click the Restore button.

Did You Know?

You can also use the Name and Comments fields at the bottom of the snapshot viewer to provide a meaningful name and relevant comments for any snapshot in the list.

Adding Bookmarks and Pragma Marks

Earlier in the hour, you read about the Bookmarks group, which displays bookmarks within your project and allows for simple navigation within and between files. To create a new bookmark, position your cursor in whatever portion of a file you want to mark, and then choose Add to Bookmarks from the Action menu in the toolbar (see Figure 11).

Figure 11. Create your own code bookmarks.

You’ll be prompted for a title for the bookmark, just like in Safari. After you’ve saved your bookmark, you can access it from the Bookmarks group in the Groups & Files list.

By the Way

Not only are the bookmarks Safari-like, but you’ll also notice a History pop-up menu beside the symbol jump-to menu, and, to the left of that, forward and backward arrows to take you back and forward in the history.

Another way to mark points in your code is by adding a #pragma mark directive. Pragma marks do not add any features to your application, but they can be used to create sections within your code that are displayed within the symbol menu. There are two types of pragma marks:

#pragma mark -


#pragma mark <label name>

The first inserts a horizontal line in the symbol menu; the second inserts an arbitrary label name. You can use both together to add a section heading to your code. For example, to add a section called “Methods that update the display” followed by a horizontal line, you could type the following:

#pragma mark Methods that update the display
#pragma mark -

After the pragma mark has been added to your code and saved, the symbol menu updates accordingly.

Building Applications

After you’ve completed your source code, it’s time to build the application. The build process encompasses several different steps, including compiling and linking. Compiling translates the instructions you type into something that the iPhone understands. Linking combines your code with the necessary frameworks the application needs to run. During these steps, Xcode displays any errors that it might find.

Before building an application, you must first choose what it is being built to run on: the iPhone Simulator or a physical iPhone device.

Configuring the Build Output

To choose how your code will be built, use the Overview pop-up menu at the upper left of the Xcode window. There are two main settings within this menu that you may want to change: the Active Device and the Active Configuration, visible in Figure 12.

Figure 12. Change the active SDK and configuration before building.

Use the top setting in the drop-down list (the Active Device) to choose between Device (your iPhone) and Simulator (the iPhone Simulator, explained shortly). For most day-to-day development, you’ll want to use the simulator—it is faster than transferring an application to the iPhone each time you make a simple change.

By default, you have two configurations to choose from: Release and Debug. The Debug configuration adds additional debugging code to your project to help in the debugging process. The Release configuration leaves debugging code out and is what you eventually submit to the App Store.

For most development, you can set the SDK to the iPhone Simulator and the Active Configuration to Debug unless you want to try real-world performance testing. Choose these options in Xcode now.

Building and Executing the Application

To build and run the application, click the Build and Run button on the Xcode toolbar (Command+R). Depending on the speed of your computer, this might take a minute or two for the process to complete. Once done, the application is transferred to your iPhone and started (if selected in the build configuration and connected) or started in the iPhone Simulator.

To just build without running the application (useful for checking for errors), choose Build from the Build menu. To run the application without building, choose Run from the Run menu.

Did You Know?

Quite a few intermediate files are generated during the build process. These take up space and aren’t needed for the project itself. To clean out these files, choose Clean All Targets from the Build menu.

The HelloXcode application is shown running in the iPhone Simulator in Figure 13. Try building and running your version of the application now.

Figure 13. The iPhone Simulator is a quick and easy way to test your code.

If you’ve been following along, your application should... not work! There are two problems with the code you were asked to type in earlier. Let’s see what they are.

Correcting Errors and Warnings

You may receive two types of feedback from Xcode when you build an application: errors and warnings. Warnings are potential problems that may cause your application to misbehave; they are displayed as yellow caution signs. Errors, on the other hand, are complete showstoppers. You can’t run your application if you have an error. The symbol for an error, appropriately enough, is a stop sign. A count of the warnings and errors is displayed in the lower-right corner of the Xcode window after the build completes.

If you are viewing the code that contains the error or warning, the error message is visible directly after the line that caused the problem. If you’re in another file, you can quickly jump to a list of the errors (with links to the source code in which they occurred) by clicking the error or warning count in the Xcode window. Figure 14 shows an error and a warning you should be receiving in the HelloXcode app.

Figure 14. You should be experiencing an error and a warning in HelloXcode.



Build status

The warning points out that we have an unused variable, myUnusedMessage, in the code. Remember, this is just a helpful warning, not necessarily a problem. If we choose to remove the variable, the message will go away; but even if we don’t, the application will still run. Go ahead and delete the line that reads UILabel *myUnusedMessage; in HelloXcodeAppDelegate.m. This fixes the warning, but there’s still an error to correct.

The error message reads too many arguments to function 'CGRectMake'. The reason for this is that the function takes four numbers and uses them to make a rectangle for the label—we’ve typed in five numbers. Delete the fifth number and preceding comma from the CGRectMake function.

Did You Know

If you’ve surmised that the numbers used CGRectMake are for positioning, you’re probably wondering how these numbers could apply to both the original iPhone screen and the iPhone 4. Remember that the iPhone screen is addressed through points, not pixels, and 1 point does not necessarily equal 1 pixel! In fact, on the iPhone 4, 1 point is really 4 pixels: 2 horizontal and 2 vertical!

Click Build and Run. HelloXcode should now start in the iPhone Simulator, just like what we saw in Figure 2.12.

Project Properties

Before finishing our brief tour of the Xcode interface, quickly turn your attention to a specific project component: the Info property list resource. This file, found in the Xcode Resources folder, is created automatically when you create a new project, is prefixed with the project name, and ends in Info.plist. This file contains settings that, while you won’t need right away, will be necessary for deploying an application to the App Store and configuring some functionality in later hours. Click the HelloXcode-Info.plist file in Xcode now. Your display should resemble Figure 15.

Figure 15. Project properties control a few important settings for your application.

Disclosure arrow

Add new value

To change a property value, double-click the right column and type your changes.

Setting an Application Icon

If you look closely at the Info properties for your project, you’ll notice an Icon File property that is completely blank. To set the property to the icon that you added to the project earlier this hour, we’ll need to change to this property to Icon Files rather than the singular Icon File.

Double-click the Icon File property name, and then change the name to Icon Files. The Icon Files will then display a disclosure arrow to its left (as you can see in Figure 2.15). Expand the Icon Files by clicking the arrow. Initially, there will be a single item 0 entry present. This is actually all we need to set both the icon for a regular iPhone and the iPhone 4! Double-click the field to the right of item 0 and type Icon. By setting just the base filename for the low-res icon, Xcode automatically knows to look for a similarly named Icon@2x. With a single entry, you’ve just set icons for both the original iPhone platforms and the iPhone 4!


If you add multiple items to the Icon Files property, one with the value Icon.png and one with Icon@2x.png, this will also work. The application searches the Icon Files property for icon resources that match what it thinks it needs. If it sees a file with no extension, it will automatically look for an @2x version as well. If, however, you include the extension on the file, the system will not automatically find the @2x variation!

We’ve included icon files with many of the projects in this book. You’re welcome to use ours, or create new icons on your own. “Basic” iPhone icons should be 57×57 PNG images with no special rounding or effects applied. The iPhone 4, however, looks much better with higher-resolution icons. For these devices, you’ll want a separate file sized at 114×114.

After designing the icons, there’s nothing else you need to do! The “glossy look” will automatically be applied to the icons for you. Apple also stresses that you should not manually add a black background to your icons. In iOS 4, the devices allow custom backgrounds on the home screens, making it likely that an icon with custom shadows or black backgrounds will clash with the display.

Setting a Launch Image

You must also add a “launch image” option to your project that enables you to choose a “splash-screen” image that will display as your application loads. To access this setting, again, add a new row to the Info.plist file, this time choosing Launch Image (iPhone) in the column on the left. You can then configure the image using the same technique used for adding an application icon, the only difference being a launch image should be sized to fit the iPhone’s screen dimensions.


If you do not name your launch images, Xcode will automatically look for images named Default.png and Default@2x.png to use as the launch images for your project.

In addition, you can choose from these suffixes (preceded by a hyphen): PortraitUpsideDown, LandscapeLeft, LandscapeRight, Portrait, and Landscape, to configure different launch images to appear in any orientation. If your default launch image, for example, is named “myLaunchImage.png”, you could simply add resources named “myLaunchImage-Landscape.png” and “myLaunchImage-Portrait.png” to create unique images for launching in portrait or landscape orientations. As with the icons, you can also create hi-res versions that are automatically loaded by adding @2x to the filename, ie: “myLaunchImage-Landscape@2x.png”.

Setting the Status Bar Display

Another interesting property that you may want to explore controls the status bar (the thin line with the carrier name, signal strength, and battery status at the top of the iPhone display). By default, this property isn’t present in the Info.plist file, so you’ll need to add a new row as described for the application icons.

Once a new row has appeared, click the far-left column to display all the available properties. You’ll notice that Status Bar Is Initially Hidden is an option. If selected, this property adds a check box in the far-right column that, if checked, automatically hides the iPhone status bar for your application.


The property settings we’ve covered here are the ones that relate to how your app looks on the iPhone and in the simulator.

That’s it for Xcode! There’s plenty more that you’ll find as you work with the software, but these should be the foundational skills you need to develop apps for your iPhone. We’ll round out this hour by looking at the next best thing to your phone: the Apple iPhone Simulator.

By the Way

Note that although it isn’t covered here, Xcode includes a wonderful documentation system.

Video tutorials
- How To Install Windows 8

- How To Install Windows Server 2012

- How To Install Windows Server 2012 On VirtualBox

- How To Disable Windows 8 Metro UI

- How To Install Windows Store Apps From Windows 8 Classic Desktop

- How To Disable Windows Update in Windows 8

- How To Disable Windows 8 Metro UI

- How To Add Widgets To Windows 8 Lock Screen

- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010
programming4us programming4us