Table of Contents
Title Page
Copyright Page
Preface
Is This Book for You?
What Else Do You Need?
Conventions Used in This Book
Organization
Acknowledgements
Chapter 1 - Getting Started
1.1 iOS SDK and IDE Basics
1.2 Creating Interfaces
1.3 Using the Debugger
1.4 Getting More Information
1.5 Summary
Exercises
Chapter 2 - Objective-C and Cocoa
2.1 Classes
2.2 Memory Management
2.3 Protocols
2.4 Properties
2.5 Categories
2.6 Posing
2.7 Exceptions and Errors
2.8 Key-Value Coding (KVC)
2.9 Multithreading
2.10 Notifications
2.11 Blocks
2.12 Grand Central Dispatch (GCD)
2.13 The Objective-C Runtime
2.14 Summary
Exercises
Chapter 3 - Collections
3.1 Arrays
3.2 Sets
3.3 Dictionaries
3.4 Summary
Exercises
Chapter 4 - Anatomy of an iPhone Application
4.1 Hello World Application
4.2 Building the Hello World Application
4.3 Summary
Exercises
Chapter 5 - The View
5.1 View Geometry
5.2 The View Hierarchy
5.3 The Multitouch Interface
5.4 Animation
5.5 Drawing
5.6 Summary
Exercises
Chapter 6 - Controls
6.1 The Foundation of All Controls
6.2 The Text Field
6.3 Sliders
6.4 Switches
6.5 Buttons
6.6 Segmented Controls
6.7 Page Controls
6.8 Date Pickers
6.9 Summary
Exercises
Chapter 7 - View Controllers
7.1 The Simplest View Controller
7.2 Tab-Bar Controllers
7.3 Navigation Controllers
7.4 Modal View Controllers
7.5 Summary
Exercises
Chapter 8 - Special-Purpose Views
8.1 Picker View
8.2 Progress View
8.3 Scroll View
8.4 Text View
8.5 Alert View
8.6 Action Sheet
8.7 Web View
8.8 Summary
Exercises
Chapter 9 - Table View
9.1 Overview
9.2 The Simplest Table View Application
9.3 A Table View with Both Images and Text
9.4 A Table View with Section Headers and Footers
9.5 A Table View with the Ability to Delete Rows
9.6 A Table View with the Ability to Insert Rows
9.7 Reordering Table Rows
9.8 Presenting Hierarchical Information
9.9 Grouped Table Views
9.10 Indexed Table Views
9.11 Dynamic Table Views
9.12 Whitening Text in Custom Cells
9.13 Summary
Exercises
Chapter 10 - File Management
10.1 The Home Directory
10.2 Enumerating a Directory
10.3 Creating and Deleting a Directory
10.4 Creating Files
10.5 Retrieving and Changing Attributes
10.6 Working with Resources and Low-Level File Access
10.7 Summary
Exercises
Chapter 11 - Working with Databases
11.1 Basic Database Operations
11.2 Processing Row Results
11.3 Prepared Statements
11.4 User-Defined Functions
11.5 Storing BLOBs
11.6 Retrieving BLOBs
11.7 Summary
Exercises
Chapter 12 - XML Processing
12.1 XML and RSS
12.2 Document Object Model (DOM)
12.3 Simple API for XML (SAX)
12.4 An RSS Reader Application
12.5 Putting It Together
12.6 Summary
Exercises
Chapter 13 - Location Awareness
13.1 The Core Location Framework
13.2 A Simple Location-Aware Application
13.3 Google Maps API
13.4 A Tracking Application with Maps
13.5 Working with Zip Codes
13.6 Working with the Map Kit API
13.7 Summary
Exercises
Chapter 14 - Working with Devices
14.1 Working with the Accelerometer
14.2 Working with Audio
14.3 Playing Video
14.4 Accessing Device Information
14.5 Taking and Selecting Pictures
14.6 Monitoring the Device Battery
14.7 Accessing the Proximity Sensor
14.8 Summary
Exercises
Chapter 15 - Internationalization
15.1 String Localization
15.2 Date Formatting
15.3 Number Formatting
15.4 Sorted List of Countries
15.5 Summary
Exercises
Chapter 16 - Custom User Interface Components
16.1 Text Field Alert View
16.2 Table Alert View
16.3 Progress Alert View
16.4 Summary
Exercises
Chapter 17 - Advanced Networking
17.1 Determining Network Connectivity
17.2 Uploading Multimedia Content
17.3 Computing MD5 Hash Value
17.4 Multithreaded Downloads
17.5 Push Notification
17.6 Local Notification
17.7 Large Downloads and Uploads
17.8 Sending Email
17.9 Summary
Exercises
Chapter 18 - Working with the Address Book Database
18.1 Introduction
18.2 Property Types
18.3 Accessing Single-Value Properties
18.4 Accessing Multivalue Properties
18.5 Person and Group Records
18.6 Address Book
18.7 Multithreading and Identifiers
18.8 Person Photo Retriever Application
18.9 Using the ABUnknownPerson ViewController Class
18.10 Using the ABPeoplePickerNavigationController Class
18.11 Using the ABPersonViewController Class
18.12 Using the ABNewPerson ViewController Class
18.13 Summary
Exercises
Chapter 19 - Core Data
19.1 Core Data Application Components
19.2 Key Players
19.3 Using the Modeling Tool
19.4 Create, Read, Update, and Delete (CRUD)
19.5 Working with Relationships
19.6 A Search Application
19.7 Summary
Exercises
Chapter 20 - Undo Management
20.1 Understanding Undo Management
20.2 Detailed Example
20.3 Wrapping Up
20.4 Summary
Exercises
Chapter 21 - Copy and Paste
21.1 Pasteboards
21.2 Pasteboard Items
21.3 The Editing Menu
21.4 Putting It Together
21.5 Summary
Exercises
Chapter 22 - Offline Mode
22.1 Setting Up the Project
22.2 Parsing XML Using the TouchXML Wrapper
22.3 Showing a Screen Shot of the Last Session
22.4 The TableView Controller
22.5 Summary
Exercises
Chapter 23 - Peer-to-Peer Communication
23.1 Basic Chat Application
23.2 Exchanging Pictures
23.3 Summary
Exercises
Chapter 24 - Developing for the iPad
24.1 The Cities App: Iteration 1
24.2 The Cities App: Iteration 2
24.3 Split View Controller
24.4 Modal View Controller Presentation Styles
24.5 Summary
Exercises
Appendix A - Saving and Restoring App State
Appendix B - Invoking External Applications
Appendix C - App Store Distribution
Appendix D - Using XCode
Appendix E - Unit Testing
Appendix F - Working with Interface Builder
REFERENCES AND BIBLIOGRAPHY
Index
Preface
Welcome to Advanced iOS 4 Programming, a text that targets the development of mobile applications on devices (such as the iPhone, iPad, and iPod touch) running the iOS 4 operating system.
This text covers a wide variety of essential and advanced topics, including
• The Objective-C programming language and runtime
• Collections
• Cocoa Touch
• Interface Builder
• Building advanced mobile user interfaces
• Core Animation and Quartz 2D
• Model-view-controller (MVC) designs
• Table views
• Core Data
• Developing for the iPad
• Grand Central Dispatch
• File management
• Parsing XML documents using SAX, DOM, and TouchXML
• Working with the Map Kit API
• Remote and local push notification
• Multitasking
• Working with the address book
• Consuming RESTful web services
• Blocks (closures) in Objective-C
• Building advanced location-based applications
• Developing database applications using the SQLite engine
• Cut, copy, and paste
• GameKit framework
• Undo management
• Unit testing
• Advanced networking
• Internationalization
• Building multimedia applications
Is This Book for You?
This book is aimed primarily at application developers with a basic understanding of the C language and object-orientation concepts such as encapsulation and polymorphism. You don’t need to be an expert C coder to follow this book. All you need is a basic understanding of structures, pointers, and functions. That said, you will find coverage of general topics such as databases and XML processing. These topics are covered assuming basic knowledge.
What Else Do You Need?
To master iPhone SDK programming, you will need the following:
• An Intel-based Mac running Mac OS X Snow Leopard.
• iOS SDK 4. Download from http://developer.apple.com/iphone.
• Optional: membership of the iPhone Developer Program so that you can use the device for development. (You will need to pay a fee for membership.)
• Source code. The source code of the applications illustrated in this book is available online at http://code.google.com/p/iphone4/.
Conventions Used in This Book
Constant width type is used for
• Code examples and fragments
• Anything that might appear in a program, including operators, method names, function names, class names, and literals
Constant-width bold type is used for
• C, Objective-C, SQL, HTML, and XML keywords, whether in text or in a program listing
Italic type is used for
• New terms and concepts when they are introduced
• Specifying emphasis in text
Organization
Chapter 1 This chapter serves as a quick introduction to the tools bundled with the SDK. It also shows you the basic development phases, including coding, UI design, and debugging.
Chapter 2 This chapter presents the main features of the Objective-C language under the Cocoa environment. We introduce the main concepts behind classes in Objective-C. You will learn how to declare a new class, define it, and use it from within other classes. You will also be exposed to important Cocoa classes and data types. You will learn about memory management in iOS4. You will learn how to create new objects as well as how to deallocate them. You will also learn about your responsibility when obtaining objects from Cocoa frameworks or other frameworks. We also introduce the topic of Objective-C protocols. You will learn how to adopt protocols and how to declare new ones as well. This chapter also covers language features such as properties, categories, and posing. Exceptions and error handling techniques are both covered in this chapter, and you will be exposed to the concept of key-value coding (KVC). You will also learn about blocks, how to utilize multithreading (including Grand Central Dispatch), and use notifications, and will be exposed to the Objective-C runtime system.
Chapter 3 This chapter addresses the topic of collections in Cocoa. It discusses arrays, sets, and dictionaries. You will learn about immutable and mutable collections, the different approaches used for copying collections, and several sorting techniques.
Chapter 4 In this chapter, we discuss the basic steps needed to build a simple iPhone application. First, we demonstrate the basic structure of a simple iPhone application and then we show the steps needed to develop the application using XCode.
Chapter 5 This chapter explains the main concepts behind views. You will learn about view geometry, view hierarchy, the multitouch interface, animation, and basic Quartz 2D drawing.
Chapter 6 In this chapter, you will learn about the base class for all controls, UIControl, and the important target-action mechanism. This chapter also presents several important graphical controls that can be used in building attractive iPhone applications.
Chapter 7 In this chapter, you will learn about the available view controllers that are provided to you in the iPhone SDK. Although you can build iPhone applications without the use of these view controllers, you shouldn’t. As you will see in this chapter, view controllers greatly simplify your applications. This chapter provides a gentle introduction to view controllers. After that, detailed treatment of tab-bar controllers, navigation controllers, and modal view controllers is provided.
Chapter 8 In this chapter, we present several important subclasses of the UIView class. We discuss picker views and show how they can be used for item selection. We investigate progress views and also talk about activity indicator views. After that, we show how to use scroll views in order to display large views. Next, we present text views used in displaying multiline text. After that, we show how to use alert views for the display of alert messages to the user. Similar to alert views are action sheets, which are also discussed. We also deal with several aspects of web views.
Chapter 9 This chapter will take you on a step-by-step journey through the world of table views. We start by presenting an overview of the main concepts behind table views. After that, we present a simple table view application and discuss the mandatory methods you need to implement in order to populate and respond to users’ interactions with the table view. We show how easy it is to add images to table rows. We introduce the concept of sections and provide a table view application that has sections, with section headers and footers. We introduce the concept of editing a table view. An application that allows the user to delete rows is presented and the main ideas are clarified. We address the insertion of new rows in a table view. An application is discussed that presents a data entry view to the user and adds that new data to the table’s rows. We continue our discussion of editing mode and present an application for reordering table entries. The main concepts of reordering rows are presented. We discuss the mechanism for presenting hierarchical information to the user. An application that uses table views to present three levels of hierarchy is discussed. We deal with grouped table views through an example. After that, we present the main concepts behind indexed table views. Next, we present a dynamic table view controller class that can be used to show cells with varying heights. Finally, we address the issue of turning the text color to white when a custom cell is selected.
Chapter 10 This chapter covers the topic of file management. Here, you will learn how to use both high- and low-level techniques for storing and retrieving file data. First, we talk about the Home directory of the application. Next, we show how to enumerate the contents of a given directory using the high-level methods of NSFileManager. You will learn more about the structure of the Home directory and where you can store files. After that, you will learn how to create and delete directories. Next, we cover the creation of files. We also cover the topic of file and directory attributes. You will learn how to retrieve and set specific file and directory attributes in this chapter. We also demonstrate the use of application bundles and low-level file access.
Chapter 11 In this chapter, we will cover the basics of the SQLite database engine that is available to you in the iPhone SDK. SQLite is an embedded database in the sense that there is no server running, and the database engine is linked to your application. First, we describe basic SQL statements and their implementation using SQLite function calls. Second, we discuss handling of result sets generated by SQL statements. Third, we address the topic of prepared statements. Fourth, we talk about extensions to the SQLite API through the use of user-defined functions. Finally, we present a detailed example for storing and retrieving BLOBs.
Chapter 12 In this chapter, you will learn how to effectively use XML in your iPhone application. The chapter follows the same theme used in other chapters and exposes the main concepts through a working iPhone application: an RSS feed reader. First, we explain the main concepts behind XML and RSS. Next, we present a detailed discussion of DOM and SAX parsing. After that, we present a table-based RSS reader application. Finally, we provide a summary of the main steps you need to take in order to effectively harness the power of XML from within your native iPhone applications.
Chapter 13 In this chapter, we will address the topic of location awareness. First, we will talk about the Core Location framework and how to use it to build location-aware applications. After that, we will discuss a simple location-aware application. Next, we cover the topic of geocoding. You will learn how to translate postal addresses into geographical locations. You will also learn how to sample movement of the device and display that information on maps. Next, we discuss how to relate zip codes to geographical information. Finally, we show you how to utilize the Map Kit API to add an interactive map to your view hierarchy.
Chapter 14 In this chapter, we demonstrate the use of the several devices available on the iPhone. We discuss the use of the accelerometer, show how to play small sound files, and show how to play video files. After that, we discuss how to obtain iPhone and iPod touch device information. Using the built-in camera and the photo library are also discussed in this chapter. After that, we show you how to obtain state information regarding the battery of the device. Finally, we discuss the proximity sensor.
Chapter 15 In this chapter, we start by looking at a step-by-step procedure for localizing strings for a set of supported languages. Next, we look at date formatting. After that, we cover formatting currencies and numbers. Finally, we discuss how to generate a sorted list of countries.
Chapter 16 In this chapter, we show how to marry various UI components and build custom reusable ones. First, we show how to build an alert view with a text field in it. Next, we present a table view inside an alert view. Finally, we show how to build a progress alert view.
Chapter 17 This chapter addresses several advanced networking topics. We start by looking at how we can determine network connectivity of the device. After that, we tackle the issue of uploading multimedia content (e.g., photos) to remote servers. Next, we present a category on NSString that allows you to easily compute the MD5 digest of a string. This is important as some services, such as Flickr, require posting parameters with the appropriate signature. After that, we show you how to present a responsive table view whose data rows are fed from the Internet without sacrificing the user experience. Next, we address the topic of remote and local push notifications. After that, we tackle some aspects of multitasking and use it in downloading a large file after the application is suspended. Finally, we discuss sending email from within an iPhone application.
Chapter 18 In this chapter, we discuss the foundation of the address book API and several UI elements that can be used to modify the contacts database. First, we provide a brief introduction to the subject. Next, we discuss property types. After that, we show how to access single-value and multivalue properties. Next, we go into the details of the person record and the address book. Issues related to multithreading and identifiers are then addressed. After covering the foundation of the address book API, we provide several sample applications.
Chapter 19 In this chapter, you learn how to use the Core Data framework in your application. First, you learn about the main components of the Core Data application. Next, we talk about the major classes in the Core Data framework. After that, you learn how to use the graphical modeling tool to build a data model. Next, we address the basic operations in persistence storage using Core Data. After that, we show how to use relationships in the Core Data model. Finally, we present a search application that utilizes Core Data for storage.
Chapter 20 In this chapter, you learn about undo management support in iOS. First, we discuss the basic steps needed to utilize undo management. After that, we present a detailed example that shows how to use undo management. Finally, we summarize the main rules in using the undo capabilities in an application.
Chapter 21 This chapter examines the copy and paste capabilities of iOS and the supporting APIs. We start by discussing pasteboards. Next, you learn about pasteboard items and the various methods available to you to manipulate them. After that, we address the subject of the editing menu, which allows users to issue editing commands. Finally, we put all the ideas behind copy and paste together and present a simple image editing application.
Chapter 22 This chapter presents several techniques that can help you develop applications that are graceful under bad network connectivity conditions.
Chapter 23 In this chapter, you learn how to use the GameKit framework to build applications that talk to each other over Bluetooth technology. This technology is used to communicate small amounts of data. We show you how to develop a simple chat application for transmitting text and small images between two iPhones.
Chapter 24 In this chapter, we investigate the different view controllers available on the iPad. You learn about popovers, split view controllers, and different presentation styles for modal view controllers.
Appendix A In this appendix, you will learn how to use property lists for saving and restoring the application state. This will give the user the illusion that your application does not quit when he or she hits the Home button.
Appendix B Here, you will learn how to programmatically invoke iPhone applications from within your application. In addition, you will learn how to publish services that other iPhone applications can utilize.
Appendix C This appendix explains the major steps needed to publish your application in the App Store.
Appendix D In this appendix, we cover several topics related to using XCode. First, we show some useful shortcuts. Next, we talk about writing custom templates for your classes, and after that we cover build configuration. Finally, we show you how to add references to other libraries (also known as frameworks).
Appendix E In this appendix, we show you how to add unit tests to your project. By adding unit testing support, you’ll be able to write tests for your business logic. These tests will be added as a dependency on the building of your application. This will result in the tests being run before you actually build your application. The appendix walks you through a step-by-step process for adding unit testing for a simple business model.
Appendix F In this appendix, we use Interface Builder to build a couple of iPhone applications. The techniques you learn from building these applications should prove to be useful in building similar iPhone applications.
Publisher’s Acknowledgments
Some of the people who helped bring this book to market include the following:
Editorial and Production
VP Consumer and Technology Publishing Director: Michelle Leete
Associate Director — Book Content Management: Martin Tribe
Associate Publisher: Chris Webb
Publishing Assistant: Ellie Scott
Project Editor: Juliet Booker
Development Editor: Kathy Simpson
Copy Editor: Kathy Simpson
Marketing
Senior Marketing Manager: Louise Breinholt
Marketing Executive: Kate Parrett
Composition Services
Compositor: Laserwords Pvt Ltd, Chennai, India
Proof Reader: Gareth Haman
Indexer: Robert Swanson
1
Getting Started
This chapter serves as a quick introduction to the tools bundled with the iOS SDK. It also shows you basic development steps used on the iOS operating system that include coding, user interface (UI) design, and debugging. You do not have to understand everything in this chapter as we will go over these concepts throughout the book. What you need to get from this chapter is a feeling for iOS development using XCode.
We start with some basics of the XCode IDE in Section 1.1. Next, Section 1.2 talks about the UI design tool Interface Builder. After that, we show you how to use the built-in debugger in XCode in Section 1.3. Next, Section 1.4 shows you different sources of information for obtaining additional help. Finally, we summarize the chapter in Section 1.5.
1.1 iOS SDK and IDE Basics
In this section, we walk you through the process of creating your first iPhone application. But first, you need to obtain the iOS SDK and install it on your Intel-based Mac.
1.1.1 Obtaining and installing the SDK
Obtaining and installing the iOS SDK is easy. Just follow these steps:
1. Get your iPhone developer Apple ID and password from: http://developer.apple.com/iphone/
2. Download the latest iOS SDK from the site mentioned above.
3. Install the iOS SDK on your Mac.
Now, you’re ready to create your first project — read on!
1.1.2 Creating a project
Let’s use XCode to create an iOS project targeting the iPhone device. First, locate XCode and launch it. You can use Spotlight to find it or you can navigate to /Developer/Applications/XCode.
XCode is the central application for writing, designing, debugging, and deploying your iOS applications. You will use it a lot, so go ahead and add it to the Dock.
From XCode, select File → New Project. You should see a window, similar to the one shown in Figure 1.1, asking you for the type of project you want to create. Choose the default and create a window-based application. This is the most generic type of iPhone project and the one that can be customized for different needs.
Figure 1.1 Choosing a window-based application in the project creation process.
Click Choose, enter the name of your project (here, we’re using My Project), and click Save. A new directory is created with the name you entered, and several files are generated for you. You should now see the newly created iPhone project as shown in Figure 1.2.
Figure 1.2 A newly created iPhone project in XCode.
1.1.3 Familiarizing yourself with the IDE
As you can see from Figure 1.2, the main window is divided into several areas. On the top, you will find the toolbar (Figure 1.3). The toolbar provides quick access to common tasks. It is fully configurable; you can add and remove tasks as you want. To customize the toolbar, Control-click it and choose Customize Toolbar. A window with a set of items will be shown so you can drag your favorite task on the toolbar. Click Done when you’re finished. To remove an item, Control-click on it and choose Remove Item.
Figure 1.3 The XCode toolbar.
On the left-hand side, you’ll see the Groups & Files list (Figure 1.4).
This list is used to organize the source code, frameworks, libraries, executables, and other types of files in your project.
The list shows several files and groups. Groups can contain other groups and files. You can delete a group as well as create a new one. The group indicated by the blue icon whose name is the same as the name you’ve chosen as the project name is a static group. Underneath it, you see all your headers, implementations, resources (images, audio files, and so on), and other related files. The folderlike yellow groups act conceptually as containers. You can have containers inside other containers and all files inside these containers live in the same directory on the disk. The hierarchy only helps you organize things. You have full freedom to organize your project’s layout as you like. The compiler will pick up the resources, headers, and implementation files when it builds your application.
Figure 1.4 The Groups & Files list in XCode.
The other kind of groups that are listed below the project group are called smart groups. There are two types of smart groups: (1) built-in smart groups and (2) custom smart groups. The content of the built-in smart groups cannot be customized. Examples of these groups include executables, bookmarks, errors/warnings, and targets. Customized smart groups are shown in purple, and two predefined groups are created for you when you create a new project. The first group is named Implementation Files, and all implementation files are listed underneath it. The other is called Nib Files, underneath which all UI files are listed.
Figure 1.5 shows the Details view and the text editor beneath it.
Selecting an item in the Groups & Files list will result in its details being shown in the Details view. You can go to a full-editor window using Command-Shift-E.
1.1.4 Looking closely at the generated code
Expand the Classes and Other Sources groups. You will notice several files that live underneath these two groups. Click on the main.m file and expand to a full-editor view.
Figure 1.5 The Details view with the text editor view.
The main.m file looks very similar to a C file with a main() function. As we will see later in this book, all that main() does is prepare for memory management and launch the application.
Click on the My_ProjectAppDelegate.h file under the Classes group. You will notice that the editor changes its content. This file contains the declaration of the application delegate class. Every application that runs on iOS has a delegate object that handles critical phases of its life cycle.
Click on My_ProjectAppDelegate.m. This file with the .m extension is the counterpart of the previous .h file. In it, you see the actual implementation of the application delegate class. Two methods of this class are already implemented for you. The applicationDid-FinishLaunching : method is one of those methods; it handles a particular phase of the application life cycle. The other method, dealloc, is a method where memory used by this object is released. In iOS, you manage the allocation and freeing of memory as there is no garbage collection. Memory management is crucial in iOS development, and mastering it is very important. The first chapters in this book are dedicated to teaching you exactly that — and much more.
The generated files and resources are adequate for starting the application. To launch the application, click on Build and Go in the toolbar or press the Command-Enter key combination. You’ll notice that the application starts in the simulator and it shows only a white screen with the status bar on top. Not very useful, but it works!
1.2 Creating Interfaces
To be useful, an iPhone application needs to utilize the amazing set of UI elements available from the SDK. Our generated iPhone application contains a single UI element: a window.
All iPhone apps have windows (usually one). A window is a specialized view that is used to host other views. A view is a rectangle piece of real estate on the 320 × 480 iPhone screen. You can draw in a view, animate a view by flipping it, and receive multitouch events on it. In iPhone development, most of your work goes towards creating views, managing their content, and animating their appearance and disappearance.
Views are arranged into a hierarchy that takes the shape of a tree. A tree has a root element and zero or more child elements. In iOS, the window is the root element and it contains several child views. These child views can in turn contain other child views and so on and so forth.
To generate views and manage their hierarchy, you can use both Interface Builder (IB) and Objective-C code. IB is an application that comes with the SDK that allows you to graphically build your view and save it to a file. This file is then loaded at runtime and the views stored within it come to life on the iPhone screen.
As we mentioned before, you can also use Objective-C code to build the views and manage their hierarchy. Using code is preferred over using IB for the following reasons. First, as a beginner, you need to understand all aspects of the views and their hierarchy. Using a graphical tool, although it simplifies the process, does hide important aspects of the process. Second, in advanced projects, your views’ layouts are not static and change depending on the data. Only code will allow you to manage this situation. Finally, IB does not support every UI element all the time. Therefore, you will sometimes need to go in there and generate the views yourself.
The following section teaches you how to use IB. However, for the most part in this book, Objective-C code is used to illustrate the UI concepts. For extensive coverage of Interface Builder, please see Appendix E.
1.2.1 Interface Builder
The project has a basic window resource file. This file can be found under the Resources group. Expand the Resources group and locate the file MainWindow.xib. This file contains the main window of the application. This file is an .xib file that stores the serialized objects in the interface. When the project is built, this file is converted to the more optimized format .nib and loaded into memory when one or more of the UI components stored in it are requested.
Double-click on the MainWindow.xib file to launch IB. IB starts by opening four windows. The first window shows the main window stored in the file. The second window shows the document window listing the different objects stored in the file. The third window is the Library window containing all the UI objects that you can add to the file. The fourth and final window is the Inspector window with its four panes.
The Inspector window shows the attributes of the currently selected object. If you click on an object, the Inspector window shows you its attributes distributed among four different panes. Each pane has several sections. You can change these attributes (such as color, position, and connections) and the changes will propagate to your project’s user interface.
The main window of the application is white; let’s change it to yellow. Click on the window object in the document window. In the Inspector window, make sure that the leftmost pane is selected. In the View section of this pane, change the background color to yellow as shown in Figure 1.6.
Figure 1.6 The attributes pane in the Inspector window of Interface Builder.
Go to XCode and run the application. Notice how the main window of the application has changed to yellow.
It is important to keep the project open in XCode while working with IB. XCode and IB communicate well when both applications are open.
To build a user interface, you start with a view and add to it subviews of different types. You are encouraged to store separate views in separate .xib files. This is important, as referencing one object in a file will result in loading all objects to main memory. Let’s go ahead and add a label view to our window. This label will hold the static text Hello iPhone.
A label is one of the many UI components available for you. These components are listed under several groups in the Library. Select Tools → Library to show the Library window if it’s not shown. As shown in Figure 1.7, locate the Inputs & Values section.
Figure 1.7 The Library window of Interface Builder.
Figure 1.8 Adding a label view to a window in IB.
Click on the Label item and drag it onto the middle of the window. Expand the dimensions of the label as shown in Figure 1.8.
When the label is selected, the Inspector window changes to reflect the attributes of the label. Figure 1.9 shows a portion of the attributes of a label in the Inspector window. You can change these attributes and observe the effect they have on the object instantaneously.
The label’s text is left-justified; let’s make it centered. In the Layout item of the attributes, click on the icon indicating center. Notice how the label text becomes centered. The text of the label can be changed in the Text item. Change Label to Hello iPhone. Go to XCode and hit Build and Go. You will notice the window showing Hello iPhone in the middle.
The text of the label is small, so let’s make it bigger. Click on the Text item and choose a text size of 48 points. Go to XCode and hit Build and Go. Figure 1.10 shows a screen shot of the completed Hello iPhone application.
Congratulations on your first successful iPhone application!
1.2.2 Revising the application
You deliver the product to the client and he is happy. However, he wants the application to have more interaction with the user. He asks you to revise the application by adding a button that the user can tap on to change the text displayed in the label.
Figure 1.9 Attributes of a label in the Inspector window.
Figure 1.10 A screen shot of the completed Hello iPhone application.
Figure 1.11 The main window after adding a new button.
Open the MainWindow. xib document (see Figure 1.2), if it is not already open. Locate the Round Rect Button item under Inputs & Values in the Library window. Drag and drop it under the label in the main window.
Change the button’s title by entering Change in the Title field of the attribute window as shown in Figure 1.11.
The main window should look like the one shown in Figure 1.12.
Now that we have a button, we want to have a method (a function) in our code to get executed when the user touches the button. We can achieve that by adding a connection between the button’s touch event and our method.
Click on the button so that it becomes selected. Click on the second pane in the Inspector window. This pane shows the connections between an object and our code. The pane should look like the one in Figure 1.13.
Now, we want to add a connection between the Touch Down event and a method we call button-Tapped. Let’s first add this method in My_ProjectAppDelegate class.
In the My_ProjectAppDelegate.h file, add the following before @end:
-(IBAction)buttonTapped;
In the My_ProjectAppDelegate.m file, add the buttonTapped method body. The My_Project-AppDelegate .m file should look something like the one in Listing 1.1.
Figure 1.12 Attributes of a button in the Inspector window.
Figure 1.13 The connections pane of our new button.
Listing 1.1 The application delegate class after adding a new method.
#import "My_ProjectAppDelegate.h"
@implementation My_ProjectAppDelegate@synthesize window;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after application launch
[window makeKeyAndVisible];
}
-(IBAction)buttonTapped{
UILabel *label = (UILabel*)[window viewWithTag:55];
if([label.text isEqualToString:@"Hello iPhone"])
label.text = @"Hello World";
else
label.text = @"Hello iPhone";
}
- (void)dealloc {
[window release];
[super dealloc];
}
@end
The buttonTapped method simply obtains a reference to the label and changes its text to either Hello World or Hello iPhone. You don’t need to understand this code at this stage. All you need to understand is that the label on the screen is encapsulated by the UILabel class and is tagged with the number 55.
Now, let’s switch to IB and add a tag to the label so that it can be retrieved from the code. Click on the label, and in the Inspector window, choose the first pane. In the second section, enter 55 for the Tag field (fourth item).
We still need to perform one last step: We need to connect the touch event with the method we just created. Click on the button and choose the connections pane (second pane). Control-click or right-click on the circle on the right-hand side of the Touch Down event; drag it on top of the My_Project App Delegate object in the Document window; and let go, as shown in Figure 1.14.
When you release the mouse, IB shows you potential methods (actions) that you can connect this event to. Right now we only have one action and that action is buttonTapped. Select that action and you’ll notice that a connection has been made as shown in Figure 1.15.
Now, switch to XCode and hit Build and Go. You’ll notice that tapping on the button changes the text value of the label.
Figure 1.14 Making a connection between an event and a method in another object.
Figure 1.15 A connection between a touch event and an action.
1.3 Using the Debugger
During the development of your applications, things often go wrong and the feature that you’ve just added does not function properly. At these moments, the built-in debugger becomes invaluable.
Let’s introduce a bug into our code. Go to My_Proj ectAppDelegate .m file, change the tag’s value used to obtain the label from 55 to 54, and click Build and Go. Now, tapping the button has no effect on the label’s text.
First, you want to make sure that the buttonTapped method gets called. In XCode, click in the left margin of the first line in the buttonTapped method as shown in Figure 1.16. After you click there, a breakpoint (shown in blue) is added.
Figure 1.16 Adding a breakpoint in the buttonTapped method.
Click Build and Go to debug the application. When the application launches, tap on the button. You’ll notice that the execution hits the breakpoint as shown in Figure 1.17. At least we know that we made our connection correctly.
Figure 1.17 Hitting a breakpoint in the buttonTapped method.
Let’s step over the statement that obtains the label from the window. Click on the Step Over button located beneath the toolbar as shown in Figure 1.18.
Figure 1.18 Step over a function or method call button.
After stepping over the statement, we need to inspect the value obtained. Hover the mouse over label in the statement just executed as shown in Figure 1.19. A tip appears, showing its value.
Figure 1.19 Inspecting the value of the label after obtaining it from the window.
Notice that the value is 0x0. In Objective-C, this value is called nil and means that no object is stored in this variable. After inspecting the tag value and going back and forth between XCode and IB, we find the problem, fix it, remove the breakpoint by clicking on it to turn it off, and hit Build and Go.
1.4 Getting More Information
There are plenty of sources for information on the SDK. These sources include the following:
• Developer documentation. The best locally stored source of information is the developer documentation. In XCode, select Help → Documentation. The documentation window appears as shown in Figure 1.20. You can search using the search box in the top-right corner for any defined type in the SDK. The documentation is hyperlinked and you can go back and forth between different pieces of information. It’s easy to use and it will become your friend.
• Developer documentation from within XCode. If you’re in XCode and you need more information about something, Option-double-click it, and the developer documentation opens with more information.
• Other help from within XCode. If you’re in XCode and you need to get the declaration and possible implementation of a given token (e.g., class, tag, variable, etc.), Command-double-click it. If there are multiple pieces of information, or disambiguation is needed, a list of items to choose among will be shown.
• iPhone Dev Center. The center is located at http://developer.apple.com/iphone/. The iPhone Dev Center has a large collection of technical resources and sample code to help you master the latest iPhone technologies.
• Apple’s forums. You can start with the site at https://devforums.apple.com/.
• The web. There is plenty of information on the web. Just enter a relevant query and let Google do its magic!
Figure 1.20 The developer documentation in XCode.
1.5 Summary
This chapter provided a gentle introduction to the world of iOS development. We showed you in Section 1.1 how to download and install the iOS SDK. After that, we iterated through the development of an iPhone application and showed you how to use Interface Builder to design user interfaces. Next, Section 1.3 discussed how to debug an iPhone application using the built-in visual debugger in XCode. You were also exposed to different sources for obtaining further help on the tools and the SDK in general in Section 1.4.
The rest of the book will detail all aspects of iOS development. However, from now on, because we want to teach you everything you need, we will stop using Interface Builder and show you how to build your UI using code. This will help you gain a solid understanding of the process. You can, of course, mix and match with Interface Builder as you wish.
The next two chapters cover the Objective-C language and the coding environment that you will be working with: Cocoa. We hope you’re as excited as we are!
Exercises
1. Check out the UILabel.h header file and read about the UILabel class in the documentation.
2. What are IBOutlet and IBAction? Command-double-click to see their definitions in the UINibDeclarations.h header file.
3. Explore the XCode IDE by reading the XCode Workspace Guide under the Help menu of the XCode application.
4. Explore Interface Builder by choosing Interface Builder Help from the Help menu of the Interface Builder application.
2
Objective-C and Cocoa
This chapter presents the main features of the Objective-C language under the Cocoa environment. Section 2.1 introduces the main concepts behind classes in Objective-C. In that section, you learn how to declare a new class, define it, and use it from within other classes. You also learn about important Cocoa classes and data types.
After that, in Section 2.2 you learn about memory management in iOS. You learn how to create new objects as well as how to deallocate them, and you also learn your responsibility when obtaining objects from Cocoa frameworks or other frameworks.
Section 2.3 introduces the topic of Objective-C protocols. There, you learn how to adopt protocols and how to declare new ones as well. Section 2.4 covers properties, an Objective-C language feature that allows you to access instance variables using the dot notation. The concept of categories is the subject of Section 2.5. Categories allow you to extend existing classes by adding new methods. Posing is another technique that is slightly different from categories. Posing allows you to replace a given class with one of its descendants. This is discussed in Section 2.6.
Exceptions and error handling are important features in any modern language. Section 2.7 covers both of these techniques and shows you the appropriate use of each feature. After viewing exceptions and errors, you are exposed to the concept of key-value coding (KVC) in Section 2.8. KVC is an important and widely used technique in Cocoa. KVC allows you to indirectly access object properties.
Next, you learn how to use multithreading in your iOS applications (Section 2.9). Cocoa makes it very easy to use multithreading and you will learn, using a step-by-step approach, how to make a task run in the background. After that, we cover the topic of notifications in Section 2.10. In Sections 2.11 and 2.12, we introduce blocks and Grand Central Dispatch. In Section 2.13, we discuss, at great length, the topic of the Objective-C runtime system. Finally, we provide a summary of this chapter in Section 2.14.
We have a lot to cover, so let’s get started.
2.1 Classes
In object-oriented languages, an object encapsulates attributes and provides methods. These methods can be used by the outside world (i.e., other objects) to change the object’s state as well as to interact with the object. All this can be achieved without opening the actual implementation of the object’s behavior to the outside world.
In Objective-C, in order to create a new class, you first need to declare it using an interface and then define it using an implementation. The declaration and the definition are usually written in two separate files. The declaration part (described more fully in the following sections) is customarily done in a .h file having the same name as the class, while the implementation, which also has the same name as the class, is in a .m file. Both the declaration and the definition parts use compiler directives. A compiler directive is an instruction to the Objective-C compiler prefixed by the @ sign. The declaration is signaled to the compiler using the @interface directive, while the actual definition is signaled using the @implementation directive.
2.1.1 Class declaration
To declare a class, MyClassName, as a subclass of class MyParentName, you simply write
@interface MyClassName : MyParentName{
// attribute declarations
}
// method declarations
@end
Here, we are telling the compiler that a new class type, MyClassName, is being declared. MyClassName is a subclass of the MyParentName class. In addition, we list the definition of all instance variables between the curly brackets. The methods are declared between the end of the curly bracket and the @end compiler directive.
There are a few important aspects of the
@interface declaration:
• The attributes declared between the curly brackets are instance variables. At runtime, every class has a unique class object and zero or more instances of the class. Every instance (object) of My Class Name has its own values for these attributes. The unique class object has no access to these instance variables.
• Methods declared can be either instance methods or class methods. An instance method is called by sending a
message to an actual instance (i.e., an object) of the class. A class method does not require a class instance. You call a class method by sending a message to the unique class object. In Objective-C, every class has exactly one class object during the runtime of the program. An instance method is declared/defined by a
- prefix, while a class method is declared/defined by a
+ prefix.
For example:
-(Address *) getAddress;
is an instance method, while
+(id) getANewInstance;
is a class method.
• Objective-C does not support class variables. However, you can use the familiar static keyword in an implementation file of a given class. This will allow instance methods (i.e., those with a - prefix in their definition) to have access to the single value of this variable shared by all instances of that declared class. If you define a static variable inside a method, then that method is the only method that has access to that variable. If you put the definition of the static variable outside the class implementation, then all methods have access to that variable.
2.1.2 How do I use other declarations?
As a Cocoa developer, you will need to be able to use classes that other developers have written. In addition, if the declaration and the definition of your classes are in separate files, you will need to inform the compiler about the location of the class declaration in the implementation file.
If you use the name of a class without accessing its methods or instance variables, you can just use the @class directive. This gives the compiler enough information to successfully compile the code. Usually the @class directive is used in class declarations. For example, consider the following declaration:
@class Address;
@interface Person{
Address *address;
}
@end
Here, we have a Person class declaration that uses the Address class. The compiler only needs to know that the Address is a class type. No details about the actual methods and attributes are needed because we just use the type.