00-your first iphone os application
TRANSCRIPT
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 1/64
Your First iOS ApplicationGeneral
2011-03-08
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 2/64
Apple Inc.
© 2011 Apple Inc.
All rights reserved.
No partof this publication maybe reproduced,
stored in a retrieval system, or transmitted, in
any form or by any means, mechanical,
electronic, photocopying, recording, or
otherwise, without prior written permission of
Apple Inc., with the following exceptions: Any
person is hereby authorized to store
documentation on a single computer for
personal use only and to print copies of
documentation for personal use provided that
the documentation contains Apple’scopyright
notice.
The Apple logo is a trademark of Apple Inc.
No licenses, express or implied, are grantedwith respectto anyof thetechnology described
in this document. Apple retains all intellectual
property rights associated withthe technology
described in this document. This document is
intended to assist application developers to
develop applications only for Apple-labeled
computers.
Apple Inc.
1 Infinite Loop
Cupertino, CA 95014
408-996-1010
App Store is a service mark of Apple Inc.
Apple, the Apple logo, Cocoa, Cocoa Touch,Instruments, iPhone, Mac, Objective-C, and
Xcode are trademarks of Apple Inc., registered
in the United States and other countries.
iPad is a trademark of Apple Inc.
IOS is a trademark or registered trademark of
Ciscoin theU.S.and othercountriesand isused
under license.
Even though Apple has reviewed this document,APPLEMAKESNO WARRANTYOR REPRESENTATION,EITHER EXPRESS OR IMPLIED, WITH RESPECT TOTHIS DOCUMENT, ITS QUALITY, ACCURACY,MERCHANTABILITY, OR FITNESSFOR A PARTICULARPURPOSE. AS A RESULT, THIS DOCUMENT ISPROVIDED “AS IS,” ANDYOU,THE READER, AREASSUMING THEENTIRE RISK AS TO ITSQUALITYAND ACCURACY.
IN NO EVENT WILL APPLE BE LIABLEFOR DIRECT,INDIRECT, SPECIAL, INCIDENTAL, ORCONSEQUENTIAL DAMAGESRESULTING FROM ANYDEFECT OR INACCURACY IN THISDOCUMENT,evenif advised of the possibility of such damages.
THEWARRANTY ANDREMEDIES SETFORTH ABOVEARE EXCLUSIVEAND INLIEUOF ALLOTHERS,ORALOR WRITTEN, EXPRESS OR IMPLIED.No Appledealer, agent,or employee is authorized to makeanymodification, extension, or addition to thiswarranty.
Somestates do notallow theexclusion orlimitationof implied warranties or liability forincidental orconsequential damages,so the abovelimitation orexclusion maynot applyto you.Thiswarranty givesyouspecificlegal rights, and youmay also have
other rightswhich vary from state to state.
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 3/64
Contents
Introduction Introduction 7
Organization of This Document 8
Chapter 1 Creating Your Project 11
Xcode 11
Application Bootstrapping 14
Recap 16
Chapter 2 Understanding Fundamental Design Patterns 17
Delegation 17
Model-View-Controller 17
Target-Action 18
Other Design Patterns 18
Chapter 3 Adding a View Controller 19
Adding a View Controller Class 19
Adding a View Controller Property 22
Creating the View Controller Instance 23
Setting Up the View 24
Housekeeping 25
Implementation Source Listing 26
Test the Application 27
Recap 28
Chapter 4 Inspecting the Nib File 29
A View Controller’s View Often Comes from a Nib File 29
File’s Owner 30
The View Outlet 31
Test the Application 32
Recap 34
Chapter 5 Configuring the View 35
Adding the User Interface Elements 35
Make Connections 39
Make the Text Field’s Delegate Connection 43
Testing 44
32011-03-08 | © 2011 Apple Inc. All Rights Reserved.
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 4/64
Recap 45
Chapter 6 Implementing the View Controller 47
The User’s Name Property 47
The changeGreeting: Method 48
Configure the View Controller as the Text Field’s Delegate 49
Test the Application 50
Recap 51
Chapter 7 Troubleshooting 53
Code and Compiler Warnings 53
Check the Nib Files 53
Delegate Method Names 53
Chapter 8 Next Steps 55
Improve the User Interface 55
Create User Interface Elements Programmatically 55
Install the Application on a Device 56
Add More Functionality 56
Add Unit Tests 57
Appendix A Code Listings 59
HelloWorldAppDelegate 59
The header file: HelloWorldAppDelegate.h 59
The implementation file: HelloWorldAppDelegate.m 59
MyViewController 60
The header file: MyViewController.h 60
The implementation file: MyViewController.m 60
Document Revision History 63
42011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CONTENTS
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 5/64
Figures
Chapter 3 Adding a View Controller 19
Figure 3-1 MyViewController 20
Figure 3-2 MyViewController 21
52011-03-08 | © 2011 Apple Inc. All Rights Reserved.
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 6/64
62011-03-08 | © 2011 Apple Inc. All Rights Reserved.
FIGURES
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 7/64
This tutorial shows how to create a simple iOS application. It has a text field, a label, and a button. You can
type your name into the text field and tap the button to say hello. The application updates the label’s text
to say “Hello, <Name>!”:
The goal is not to create a finely polished application, or on the other hand to get an application on screen
as quickly as possible, but to illustrate the Three T’s:
● Tools: How you create and manage a project using Xcode
● Technologies: How to make your application respondto user input usingstandarduser interface controls
● Techniques: The fundamental design patterns and techniques that underlie all Mac OS X development
72011-03-08 | © 2011 Apple Inc. All Rights Reserved.
INTRODUCTION
Introduction
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 8/64
A secondary goal is to point out other documents that you must also read to fully understand the iOS
development tools and techniques.
You should read this document if you are just starting development for iOS. You should use this tutorial to
get started even if you intend to develop solely for the iPad. Although the tutorial shows the iPhone user
interface, thetools and techniques you useare exactly thesame as those you useto developiPadapplications.
You must, though, already have some familiarity with the basics of computer programming in general and
the Objective-C language in particular. If you haven’t used Objective-C before, read through at least Learning
Objective-C: A Primer .
Important: To follow this tutorial, you must have installed the iPhone SDK and developer tools available
from the iOS Dev Center.
This document describes the tools that are available for iPhone SDK v4.3 and later—check that your version
of Xcode is at least 4.0.
To learn more about the technologies in Cocoa Touch, read iOS Technology Overview .
In this tutorial, little regard is given to the user interface. Presentation is, however, a critical component of a
successful iOS application. You should read the iOS Human Interface Guidelines to understand how the user
interface might be improved for a full-fledged application.
This tutorial does notdiscuss issuesbeyondbasic application development; in particular, it does notdescribe
how to submit applications to the App Store.
Organization of This Document
The tool you use to create Mac OS X applications is Xcode—Apple’s IDE (integrated development environment).
“Creating Your Project” (page 11) shows you how to create a new project and describes how an application
launches.
Whereas Xcode is the application you use to create and manage the project, Cocoa is the name given to the
collection of APIs that you use to develop programs for Mac OS X. You should typically use the highest level
of abstraction available to accomplish whatever task you want to perform. To create a desktop application,
you should use the Objective-C-based frameworks that provide the infrastructure you need to implement
graphical, event-driven applications.
To use the Objective-C frameworks effectively, you need to follow a number of conventions and design
patterns. Following the Model-View-Controller (or “MVC”) design pattern, the application uses a controller
object to mediate between the user interface (view objects) and the underlying representation of a track (a
model object).
● “Understanding Fundamental Design Patterns” (page 17) provides an overview of the design patterns
you’ll use.
● “Adding a View Controller” (page 19) shows you how to customize a view controller class and create an
instance of it.
You design the user interface graphically, using Xcode, rather than by writing code. The interface objects are
stored in an archive called a nib file.
8 Organization of This Document2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
INTRODUCTION
Introduction
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 9/64
Terminology: Although an interface document may have a “.xib” extension, historically the extension was
“.nib” (an acronym for “NextStep Interface Builder”) so they are referred to colloquially as “Nib files.”
The nib file doesn’t just describe the layout of user interface elements, it also defines non-user interface
elements and connections between elements. The controller object is represented in the nib file. At runtime,when a nib file is loaded the objects are unarchived and restored to the state they were in when you saved
the file—including all the connections between them.
● “Inspecting the Nib File” (page 29) introduces you to two important concepts: outlets, and the File’s
Owner proxy object
● “Configuring the View” (page 35) shows you how to add and configure the button and text fields.
● “Implementing the View Controller” (page 47) walks you through implementing the view controller,
including memory management, the changeGreeting:method, and ensuring that the keyboard is
dismissed when the user taps Done
● “Troubleshooting” (page 53) describes some approaches to solving common problems that you may
encounter.
● “Next Steps” (page 55) offers suggestions as to what directions you should take next in learning about
iOS development.
Organization of This Document 92011-03-08 | © 2011 Apple Inc. All Rights Reserved.
INTRODUCTION
Introduction
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 10/64
10 Organization of This Document2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
INTRODUCTION
Introduction
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 11/64
In this chapter, you create the project using Xcode and find out how an application launches.
Xcode
The main tool you use to create applications for iOS is Xcode—Apple’s IDE (integrated development
environment). You canalso use it to create a variety of other projecttypes, including Cocoa and command-line
utilities.
To create a new project . . .
1. Launch Xcode.
By default it’s in /Developer/Applications.
2. Create a new project by choosing File > New Project.
You should see a new window similar to this:
Xcode 112011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 1
Creating Your Project
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 12/64
3. In the left pane, choose iOS application.
4. Select Window-based Application then click Next.
5. In the Device popup menu, make sure iPhone is selected.
Do not select the option to use Core Data. The tutorial does not use Core Data.
Do not select the option to use unit tests. The tutorial doesn’t discuss how to set up unit tests; however,
you should consider using unit tests a best practice for Cocoa development.
6. Enter HelloWorld as the product name, and a suitable company identifier (if you don’t have one, use
edu.self).
Note: Theremainder of thetutorialassumes that you namedtheprojectHelloWorld, so theapplication
delegate class is called HelloWorldAppDelegate. If you name your project something else, then the
application delegate class will be called YourProjectNameAppDelegate.
7. Click Next.
A sheet appears to allow you to select where your project will be saved.
8. Select a suitable location for your project (such as the Desktop or a custom Projects directory), then click
Save.
You do not need to create a version control repository for this project, although in general you are
encouraged to do so.
12 Xcode2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 1
Creating Your Project
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 13/64
You should see a new project window like this:
If you haven’t used Xcodebefore, take a moment to explore the application. You should read Xcode WorkspaceGuide to understand the organization of the project window and how to perform basic tasks like editing and
saving files. You can now build and run the application to see what Simulator looks like.
To run your application in Simulator . . .
● Choose Product > Run (or click the Run button in the toolbar).
The iOS Simulator application should launch automatically, and when your application starts up you should
simply see a white screen:
Xcode 132011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 1
Creating Your Project
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 14/64
To understand where the white screen came from, you need to understand how the application starts up.
For now, quit Simulator.
To quit Simulator . . .
● Choose Simulator > Quit.
Application Bootstrapping
Thetemplate project you created already sets up the basic application environment. It creates an application
object, connects to the window server, establishes the run loop, and so on. Most of the work is done by the
UIApplicationMain function.
The main function in main.m calls the UIApplicationMain function:
14 Application Bootstrapping2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 1
Creating Your Project
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 15/64
int retVal = UIApplicationMain(argc, argv, nil, nil);
This creates an instance of UIApplication. It also scans the application’s Info.plist property list file.
The Info.plist file is a dictionary that contains information about the application such as its name and
icon. It may contain the name of the nib file the application object should load, specified by the
NSMainNibFile key. Nib files contain an archive of user interface elements and other objects—you’ll learn
more about them later in the tutorial. In your project’s Info.plist file you should see:
ValueKey
MainWindowNSMainNibFile
This means that when the application launches, the MainWindow nib file is loaded.
To look at the main nib file . . .
● Click MainWindow.xib in the Resources group in the project window
The file has the extension “xib” but by convention it is referred to as a “nib file”. Xcode displays the file
in the editor area.
The nib file contains several items split into two groups by a dividing line. Above the line are placeholders:
Application Bootstrapping 152011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 1
Creating Your Project
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 16/64
● The File’s Owner proxy object (the pale yellow cube).
The File’s Owner object is actually the UIApplication instance—File’s Owner is discussed later, in
“File’s Owner” (page 30).
● A First Responder proxy object.
The First Responder is not used in this tutorial but you can learn more about it by reading “The
Event-Handling System” in iOS Application Programming Guide.
Below the line are actual objects:
● An instance of HelloWorldAppDelegate set to be the application’s delegate.
Delegation is explained in more detail in “Understanding Fundamental Design Patterns” (page 17).
● A window.
The window has its background set to white and is set to be visible at launch. It ’s this window that you
see when the application launches.
You use the application delegate to perform custom configuration for the application as a whole, including
displaying the window. It shouldn’t, though, manage any of the content on the screen beyond the window
itself—that’s the job of view controllers. A view controller is a special controller responsible for managing
a view—this adheresto themodel-view-controllerdesign pattern (explained in more detail in “Understanding
Fundamental Design Patterns” (page 17)).
When the application object has completed its setup, it sends its delegate an
application:didFinishLaunchingWithOptions:message. This gives the delegate an opportunity to
configure the user interface and perform other tasks before the application is displayed.
Recap
In this chapter you created a new project using Xcode and built and ran the default application. You also
looked at some of the basic pieces of a project and a nib file, and learned how the application starts up. In
the next chapter, you’ll learn about the design patterns you use when developing a Cocoa application.
16 Recap2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 1
Creating Your Project
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 17/64
In this chapter, you learn about the main design patterns you’ll use in Cocoa applications. There’s not much
practical to do in this chapter, but the concepts are fundamental, so allow some time to read and think about
it.
The main patterns you’re going to use in this tutorial are:
● Delegation
● Model-View-Controller
● Target-Action
Here’s a quick summary of these patterns and an indication of where they’ll be used in the application.
Delegation
Delegation is a pattern in which one object sends messages to another object specified as its delegate to
ask for input or to notify the delegate that an event is occurring. You typically use it as an alternative to class
inheritance for extending the functionality of reusable objects.
In this application, the application object tells its delegate that the main start-up routines have finished and
that the custom configuration can begin. For this application, you want the delegate to create an instance
of a controller to set up and manage the view. In addition, the text field will tell its delegate (which in this
case will be the same controller) when the user has tapped the Return key.
Delegate methods aretypically grouped together into a protocol.A protocol is basically just a list of methods.
If a class conforms to (or “adopts”) a protocol, it guarantees that it implements the required methods of a
protocol. (Protocols may also include optional methods.) The delegate protocol specifies all the messages
an object might send to its delegate. To learn more about protocols and the role they play in Objective-C,
see the “Protocols” chapter in The Objective-C Programming Language.
Model-View-Controller
The Model-View-Controller (or “MVC”) design pattern sets out three roles for objects in an application.
Model objects represent data such as SpaceShips and Weapons in a game, ToDo items and Contacts in a
productivity application, or Circles and Squares in a drawing application.
Delegation 172011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 2
Understanding Fundamental Design Patterns
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 18/64
In this application, the model is very simple—just a string—and it’s not actually used outside of a single
method, so from a practical perspective in this application it’s not even necessary. It’s the principle that’s
important here, though. In other applications the model will be more complicated and accessed from a
variety of locations.
View objects know how to display data (model objects) and may allow the user to edit the data.
In this application, you need a main view to contain several other views—a text field to capture information
from the user, a second text field to display text based on the user’s input, and a button to let the user tell
us that the secondary text should be updated.
Controller objects mediate between models and views.
In this application, the controller object takes the data from the input text field, stores it in a string, and
updates a second text field appropriately. The update is initiated as a result of an action sent by the button.
Target-Action
The target-action mechanism enables a view object that presents a control—that is, an object such as a
button or slider—in response to a user event (such as a click or a tap) to send a message (the action) to
another object (the target) that caninterpret themessage andhandle it as an application-specific instruction.
In this application, when it’s tapped, the button tells the controller to update its model and view based on
the user’s input.
Other Design Patterns
Cocoa makes pervasive use of a number of design patterns beyond those described above. The design
patterns chapter in Cocoa Fundamentals Guide provides a comprehensive overview of all the design patterns
you use in Cocoa application development—you should consider it to be essential reading. Understanding,
andusing, the patterns will make it easier for you to usethe various technologies Cocoa provides, andtransfer
skills you’ve learned in one are to another. Following the patterns also means that your code will work better
with Cocoa.
18 Target-Action2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 2
Understanding Fundamental Design Patterns
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 19/64
In this application you’ll need two classes. Xcode’s application template provided an application delegate
class and an instance is created in the nib file. You need to implement a view controller class and create an
instance of it.
Adding a View Controller Class
View controller objects play a central role in most iOS applications. As the name implies, they’re responsible
for managing a view, but on iOS they also help with navigation and memory management. You’re not going
to use the latter features here, but it’s important to be aware of them for future development. UIKit providesa special class—UIViewController—that encapsulates most of the default behavior you want from a view
controller. You have to create a subclass to customize the behavior for your application.
To add a custom view controller class . . .
1. In Xcode, in the project organizer select either the project (HelloWorld at the top of the Groups and
Files list) or the HelloWorld group folder.
The new files will be added to the current selection.
2. Choose File > New File and in the New File window.
You should see a sheet like this:
Adding a View Controller Class 192011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 3
Adding a View Controller
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 20/64
3. Select the Cocoa Touch Classes group, then select UIViewController subclass.
4. Click Next.
You should see a sheet like this:
Figure 3-1 MyViewController
20 Adding a View Controller Class2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 3
Adding a View Controller
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 21/64
5. Using the combo box, choose to create a subclass of UIViewController.
6. Using thecheckboxes,make sure that Targeted for iPad is not selected,and that With XIB for user interface
is selected.
7. Click Next.
You should see a sheet like this:
Figure 3-2 MyViewController
Make sure the Add to targets check box is selected.
8. Give the file a new name such as MyViewController.
By convention, class names begin with a capital letter.
9. Click Save.
Make sure that the files were added to your project.
If you look at the new source files, you’ll see that stub implementations of various methods are already givento you. These are all you need for the moment; the next task is to create an instance of the class.
Adding a View Controller Class 212011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 3
Adding a View Controller
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 22/64
Adding a View Controller Property
You want to make sure that the view controller lasts for the lifetime of the application, so it makes sense to
add it as a property of the application delegate (which will also last for the lifetime of the application). (To
understand why, consult Memory Management Programming Guide.)
Perform thefollowingtasks in theheader filefor theapplication delegate class (HelloWorldAppDelegate.h).
To add a view controller property . . .
1. Add a forward declaration for the MyViewController class.
Before the interface declaration for HelloWorldAppDelegate, add:
@class MyViewController;
The property will be an instance of the MyViewController class. The compiler will generate an error,
though, if you declare the variable but you don’t tell it about the MyViewController class. You could
import the header file, but typically in Cocoa you instead provide a forward declaration—a promise to
the compiler that MyViewControllerwill be defined somewhere else and that it needn’t waste time
checking for it now. (Doing this also avoids circularities if two classes need to refer to each other and
would otherwise include each other’s header files.) Later, you will import the header file itself in the
implementation file.
2. Add a declaration for the view controller property. After the closing brace but before @end, add:
@property (nonatomic, retain) MyViewController *myViewController;
Important: Like C, Objective-C is case-sensitive.MyViewController refers to a class; myViewController
is a variable that here contains an instance of MyViewController. A common programming error in Cocoa
is to misspell a symbol name, frequently by using a letter of an inappropriate case (for example, “tableview”
instead of “tableView”). This tutorial deliberately uses MyViewController and myViewController to
encourage you to look at the name carefully. When writing code, make sure you use the appropriate symbol.
Properties are described in the “Declared Properties” chapter in The Objective-C Programming Language.
Basically, though, this declaration specifies that an instance of HelloWorldAppDelegate has a property
that you canaccess using thegetter and setter methods myViewControllerandsetMyViewController:
respectively, and that the instance retains the property (retaining is discussed in more detail later).
To make sure you’re on track, confirm that your HelloWorldAppDelegate class interface file
(HelloWorldAppDelegate.h) looks like this (comments are not shown):
#import <UIKit/UIKit.h>
@class MyViewController;
@interface HelloWorldAppDelegate : NSObject <UIApplicationDelegate> {
22 Adding a View Controller Property2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 3
Adding a View Controller
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 23/64
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) MyViewController *myViewController;
@end
You can now create an instance of the view controller.
Creating the View Controller Instance
Now that you’ve added the view controller property to the application delegate, you need to actually create
an instance of the view controller and set it as the value for the property. To make code-completion work
for your new class in Xcode, you also need to import the relevant header file for the view controller.
Perform the following tasks in the implementation file for the application delegate class
(HelloWorldAppDelegate.m).
To import the view controller’s header file . . .
● At the top of file, add:
#import "MyViewController.h"
To add a view controller instance . . .
● Add the following code as the first statements in the implementation of the
application:didFinishLaunchingWithOptions:method:
MyViewController *aViewController = [[MyViewController alloc]
initWithNibName:@"MyViewController" bundle:[NSBundle mainBundle]];
[self setMyViewController:aViewController];
[aViewController release];
There’s quite a lot in just these three lines. What they do is:
● Create and initialize an instance of the view controller class.
● Set the new view controller to be the value of the myViewController property using an accessor
method.
Remember that you didn’t separately declare setMyViewController:, it was implied as part of the
property declaration—see “Adding a View Controller Property” (page 22).
Creating the View Controller Instance 232011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 3
Adding a View Controller
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 24/64
● Adhere to memory management rules by releasing the view controller.
You create the view controller object using alloc, then initialize it using initWithNibName:bundle:. The
init method specifies first the name of the nib file the controller should load and second the bundle in
which it should find it. A bundle is an abstraction of a location in the file system that groups code and
resourcesthatcan be usedin an application. Theadvantages of using bundles over locatingresourcesyourself in the file-system are that: bundles provide a convenient and simple API—the bundle object can locate a
resource just by name; and they take account of localization for you. To learn more about bundles, seeResource Programming Guide.
By convention, you own any objects you create using an alloc method (amongst others, see “Memory
Management Rules”). You should also:
● Relinquish ownership of any objects you create.
● Typically use accessor methods to set property values anywhere other than in an initializer method.
Thesecond line in the implementation uses an accessor method to set the property value, andthen thethirdline uses release to relinquish ownership.
There are other ways to implement the above. You could, for example, replace the three lines with just two:
MyViewController *aViewController = [[[MyViewController alloc]
initWithNibName:@"MyViewController" bundle:[NSBundle mainBundle]]
autorelease];
[self setMyViewController:aViewController];
In this version, you use autorelease as a way to relinquish ownership of the new view controller but at
some point in the future. To understand this, read “Autorelease Pools” in the Memory Management
Programming Guide. In general, however, you should try to avoid using autorelease wherever possible
since it means memory may be reclaimed later than it would be if you used release.
You could also replace [self setMyViewController:aViewController]; with:
self.myViewController = aViewController;
The dot notation invokes exactly the same accessor method (setMyViewController:) as in the original
implementation. The dot notation simply provides a more compact syntax for accessor methods—especially
when you use nested expressions. Which syntax you choose is largely personal preference, although using
thedotsyntaxdoes have some additional benefitswhen used in conjunctionwith properties—see“Declared
Properties” in The Objective-C Programming Language. For more about the dot syntax, see “Dot Syntax” in
The Objective-C Programming Language in “Objects, Classes, and Messaging” in The Objective-C Programming
Language.
Setting Up the View
View controllers are responsible for configuring and managing each “screenful” you see in an application.
Each screenful should be managed by a view controller. To codify this principle, a window has a root view
controller—the viewcontroller responsible for configuringthe viewfirstdisplayed when the window appears.
To get your view controller’s content into the window, you set your view controller to be the window’s root
view controller.
24 Setting Up the View2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 3
Adding a View Controller
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 25/64
To set your view controller as the window’s root view controller . . .
● Add the following line of code just before the call to makeKeyAndVisible.
self.window.rootViewController = self.myViewController;
Instead of using the dot syntax, you could also use square brackets:
[[self window] setRootViewController:[self myViewController]];
Both lines of code would compile to the same thing; again you can choose which you feel is more readable.
A further important point about this line, though, is that it uses the accessor method to retrieve
myViewController.
Tip In addition to using accessor methods to set property values (except in the implementation of aninit method), you should use accessor methods to get property values, even those of self (except in
the implementation of a dealloc method). This helps to preserve encapsulation, and in some cases
ensures that a property value is properly initialized before you try to use it. This is discussed in more
detail in “Housekeeping” (page 25).
The final line in the implementation of the application:didFinishLaunchingWithOptions:method
from the template:
[window makeKeyAndVisible];
causes the window—now complete with your view—to be displayed on screen.
Housekeeping
There are a couple of unfinished tasks to complete: You need to synthesize the accessor methods, and—to
conform to the rules of memory management—make sure the view controller is released in the dealloc
method.
You perform the following tasks in the @implementation block of the class (HelloWorldAppDelegate).
To synthesize the view controller property . . .
● Tell the compiler to synthesize the accessor methods for the view controller, and to use a custom name
for the corresponding instance variable.
@synthesize myViewController=_myViewController;
Housekeeping 252011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 3
Adding a View Controller
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 26/64
This line of code tells the compiler to do several things:
● Create accessor methods for the myViewController property.
Strictly speaking, it means “create accessor methods, according to the property declaration, for which
the developer hasn’t provided an implementation.” Since you haven’t created custom implementations,
the compiler will generate a get and set accessor. (If the property were declared as readonly, thecompiler would only generate a get accessor.)
● Use _myViewController as the name of the instance variable for the myViewController property.
● Because you didn’t declare a _myViewController instance variable, it also tells the compiler to add
that to the class as well.
You use the “_” prefix for the instance variable to serve as a reminder that you shouldn’t access an instance
variable directly. From an academic perspective, this helps to preserve encapsulation, but there are two
important practical benefits in Cocoa:
● Some Cocoa technologies (notably key-value coding) depend on use of accessor methods, and in theappropriate naming of the accessor methods. If you don’t use accessor methods, your application may
be less able to take advantage of standard Cocoa features.
● Some property values are created on-demand. If you try to use the instance variable directly, you may
get nil or an uninitialized value. (A view controller’s view is a good example.)
To complete the implementation of the dealloc method . . .
● In the dealloc method, release the view controller as the first statement.
[_myViewController release];
Implementation Source Listing
To make sure you’re still on track, confirm that your HelloWorldAppDelegate class implementation
(HelloWorldAppDelegate.m) looks like this (the methods you didn’t edit are omitted):
#import "HelloWorldAppDelegate.h"
#import "MyViewController.h"
@implementation HelloWorldAppDelegate
@synthesize window=_window;
@synthesize myViewController=_myViewController;
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
26 Implementation Source Listing2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 3
Adding a View Controller
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 27/64
{
MyViewController *aViewController = [[MyViewController alloc]
initWithNibName:@"MyViewController" bundle:nil];
self.myViewController = aViewController;
[aViewController release];
self.window.rootViewController = self.myViewController;
[self.window makeKeyAndVisible];
return YES;
}
/* Other methods omitted from the listing. */
- (void)dealloc {
[_myViewController release];
[_window release];
[super dealloc];
}
@end
Test the Application
You can now test your application.
To test the application . . .
● Compile and run the project.
Choose Product > Run (or click the Run button in Xcode’s toolbar).
Your application should compile without errors and you should again see a white screen in Simulator.
Test the Application 272011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 3
Adding a View Controller
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 28/64
Recap
In this section you addeda new view controller class and itsaccompanying nibfile. In the application delegate,
you declared an instance variable and accessor methods for a view controller instance. You also synthesized
theaccessor methods andperformeda fewother housekeeping tasks.Most importantly, though, youcreated
an instance of theview controller andpassed its to thewindow as theroot view controller. In thenext chapter
you’ll configure the nib file the controller uses to load its view.
28 Recap2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 3
Adding a View Controller
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 29/64
This chapter introduces two important concepts: outlets and the File’s Owner proxy object.
A View Controller’s View Often Comes from a Nib File
As you learned earlier, a view controller is responsible for configuring and managing each “screenful” you
see in an application. Each screenful is defined by the view controller’s view; often you configure that view
in a nib file (a common exception is a table view). Typically you specify the name of the nib file to load as
the first argument to initWithNibName:bundle: (see “Creating the View Controller Instance” (page 23)).
A view controller loads its nib file in its loadView method. (You can load nib files yourself using an instance
of NSBundle. You can learn more about loading nib files in Resource Programming Guide.) If you initialize a
view controller using initWithNibName:bundle: but you want to perform additional configuration after
the view is loaded, you override the controller’s viewDidLoad method.
The view controller’s nib file contains three objects, the File’s Owner proxy, the First Responder proxy, and
a view. You can see them by inspecting the nib file.
To inspect the nib file . . .
● In Xcode, click the view controller’s nib file (MyViewController.xib).
You should see the file displayed like this:
A View Controller’s View Often Comes from a Nib File 292011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 4
Inspecting the Nib File
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 30/64
The view is the main view for the view controller. The view controller is represented by the File’s Owner
proxy. It’s important to understand the role of File’s Owner, and how to create connections to and from both
File’s Owner and other objects.
File’s Owner
In a nib file, in contrast to the other objects you add to the interface, the File’s Owner object is not created
when the nib file is loaded. It represents the object set to be the owner in the method that loads the nib
file—inthiscase, loadNibNamed:owner:options: . This is discussed in more detail in Resource Programming
Guide. In your application, the File’s Owner will be the instance of MyViewController.
To allow you to make appropriate connections to and from the File’s Owner, Xcode has to know what sort
of object File’s Owner is. You tell Xcode the class of the object using the Identity Inspector. It was actually
set when you created the nib file together with the view controller classes, but it ’s useful to look at the
inspector now.
To show the inspector . . .
1. With the nib file selected, in Xcode display the Utilities view.
30 File’s Owner2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 4
Inspecting the Nib File
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 31/64
2. In the Inspector pane, select the Identity inspector.
In the Classfield of the CustomClass section, you shouldsee MyViewController. It’s important to understand
that this is justa promise to InterfaceBuilder that the File’s Owner will bean instance of MyViewController.Setting the class doesn’t ensure that the File’s Owner will be an instance of that class. Remember, the File’s
Owner is simplywhatever object is passedas theowner argument to theloadNibNamed:owner:options:
method. If it’s an instance of a different class, the connections you make in the nib file will not be properly
established.
The View Outlet
You canlook at—andmake andbreak—anobject’s connections using theInspector pane,or in a connections
panel.
To look at the view controller’s connections . . .
1. In the Interface Builder editor window, click File’s Owner.
2. In the Inspector pane, select the Connections inspector.
This displays File’s Owner’s outlet connections in the utility area.
The View Outlet 312011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 4
Inspecting the Nib File
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 32/64
3. In the Interface Builder editor window, Control-click File’s Owner.
This displays a translucent panel showing File’s Owner’s connections.
The utility area and the connections pane both show the same information. You can use whichever is more
convenient at any particular time.
The only connection at the moment is the view controller’s view outlet. An outlet is just a property that
happens to connect to an item in a nib file. The outlet connection means that when the nib file is loaded
and the UIView instance is unarchived, the view controller’s (strictly File’s Owner’s) view property is set to
that view.
Test the Application
To make sure your application’s workingcorrectly, youcould setthebackground color of theview to something
other than white and verify that the new color is displayed after the application launches.
To set the background color of the view controller’s view . . .
1. In Xcode, select the view controller’s nib file (MyViewController.xib).
32 Test the Application2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 4
Inspecting the Nib File
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 33/64
2. In the utilities area, select the Attributes inspector.
3. In the editor area, select the view.
4. In theAttributes inspector for theview, click the frame of the Background color well to display theColors
panel.
5. In the Colors panel, select a different color.
6. Save the nib file.
7. Click the Run button in the toolbar to compile and run the project.
Your application should compile without errors and you should again see an appropriately-colored screen
in Simulator.
To restore the view’s background color . . .
1. In Xcode, using the attributes inspector, set the view’s background color to white.
2. Save the nib file.
Test the Application 332011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 4
Inspecting the Nib File
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 34/64
Recap
In this section you inspected a nib file, learned about outlets, and set the background color of a view. You
also learned more about resource loading and how the view controller loads the nib file.
In the next chapter you will add controls to the view.
34 Recap2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 4
Inspecting the Nib File
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 35/64
Interface Builder provides a library of objects that you can add to a nib file. Some of these are user interface
elements such as buttons and text fields; others are controller objects such as view controllers. Your nib file
already contains a view—now you just need to add the button and text fields.
Adding the User Interface Elements
You add user interface elements by dragging them from the object library.
To add objects to the nib file and lay them out appropriately . . .
1. In Xcode, select the view controller’s nib file.
2. In the utilities area, display the object library.
3. Add a button (UIButton), a text field (UITextField), and a label (UILabel) to the view.
You can drag view items from the library and drop them onto the view just as you might in a drawing
application.
Adding the User Interface Elements 352011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 5
Configuring the View
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 36/64
4. Lay out the elements appropriately.
You can then resize the items using resize handles where appropriate, and reposition them by dragging.
As you move items within the view, alignment guides are displayed as dashed blue lines.
36 Adding the User Interface Elements2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 5
Configuring the View
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 37/64
5. Finalize the view.
● Add a placeholder string Your Name to the text field by entering it in the Text Field Attributes
inspector.
● Resize the label so that it extends for the width of the view.
● Delete the text (“Label”) from the label either using the Label Attributes inspector or by selecting
the text in the label itself (double-click to make a selection) and press Delete.
● Add a title to the button by double-clicking inside the button and typing Hello.
● Use the inspector to set the text alignment for the text field and label to centered.
Your view should look like this:
Adding the User Interface Elements 372011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 5
Configuring the View
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 38/64
6. In the view section of the label’s Label Attributes inspector, select Clear Context Before Drawing.
This ensures that when you update the greeting the previous string is removed before the new one is
drawn. If you don’t do this, the strings are drawn on top of each other.
There are several other changes to make to the text field—it might be fairly obvious that the first change
applies to the text field, but the others are less obvious. First, you might want to ensure that names are
automatically capitalized. Second, you might want to make sure that the keyboard associated with the text
field is configured for entering names, and that the keyboard displays a Done button.
The guiding principle here is this: You know when you’re putting it on screen what a text field will contain.
You therefore design the text field to make sure that at runtime the keyboard can configure itself to best
suit the user’s task. You make all of these settings using text input traits.
To configure the text field . . .
1. Select the text field.
2. In the utilities area, display the attributes inspector.
3. Configure the text field using the Text Input Traits.
● In the Capitalize pop-up menu, select Words.
38 Adding the User Interface Elements2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 5
Configuring the View
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 39/64
● In the Keyboard Type pop-up menu, select Default.
● In the Keyboard Return Key pop-up menu, select Done.
4. Save the nib file.
If you build and run your application in Xcode, when it launches you should see the user interface elements
as you positioned them. If you press the button, it should highlight, and if you tap inside the text field, the
keyboard should appear. At the moment, though, after the keyboard appears, there’s no way to dismiss it.
To remedy this, and add other functionality, you need to make appropriate connections to and from the
view controller. These are described in the next section.
Make Connections
You can create and connect outlets and actions in Xcode by dragging from a nib file to the appropriate
source file. Whereas this makes it easy to add code to support outlets and actions, it adds a conceptual level
of indirection. Although you’re dragging to the source file, the actual connections are made in the nib file
itself, to the object for which the header file is the declaration—in this case, the view controller represented
by File’s Owner.
You want to add an action method to the view controller; when the button is “activated” it should send a
changeGreeting: message to the view controller. For the button, you want to create an action called
changeGreeting::
To add an action for the button . . .
1. In Xcode, select the view controller’s nib file (MyViewController.xib).
2. Display the Assistant editor.
3. Make sure Assistant displays the view controller’s header file (MyViewController.h).
4. Control drag from the button in the nib file to the method declaration area in the header file.
Make Connections 392011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 5
Configuring the View
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 40/64
5. Configure the button’s connection as an action.
● Set the connection type to Action.
● Set the name to changeGreeting:.
● Set the type to id.
It doesn’t matter what sort of object sends the message.
● Set the event to touch up inside.
The message should be sent if the user lifts their finger inside the button—this corresponds to
UIControlEventTouchUpInside.
● Set the arguments to sender.
6. Click Connect.
You accomplished two things by adding an action for a button:
1. Added appropriate code to the view controller class.
You added the action method declaration to the header file:
- (IBAction)changeGreeting:(id)sender;
40 Make Connections2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 5
Configuring the View
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 41/64
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 42/64
5. Configure the text field’s connection as an outlet.
Add an outlet from the view controller connected to the text field.
● Set the connection type to Outlet.
● Set the name to textField.
You can call the outlet whatever you want, but it makes your code more understandable if the name
bears some relationship with the thing it represents.
● Set the type to UITextField.
You want to make sure the outlet can only connect to a text field.
6. Click Connect.
You accomplished two things by adding an outlet for the text field:
1. You added appropriate code to the view controller class.
The property declaration to the header file:
@property (nonatomic, retain) IBOutlet UITextField *textField;
and other code the implementation file. It adds:
@synthesize textField;
to the top of the @implementation block;
[textField release];
to the dealloc method, and
[self setTextField:nil];
to the viewDidUnload method.
Property declarations and the synthesize keyword are explained in more detail in “The User’s Name
Property” (page 47).
IBOutlet is a special keyword that is used only to tell Interface Builder to treat a property as an outlet.
It’s actually defined as nothing so it has no effect at compile time.
2. You established a connection from the the view controller (as represented by the File’s Owner) to the
text field.
Establishing a connection from thethe view controller does theequivalent of invokingsetTextField:
on the view controller, passing the text field as the argument.
Now configure the label. Follow the same steps as for the text field, but with appropriate changes to the
configuration.
42 Make Connections2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 5
Configuring the View
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 43/64
To add an outlet from the view controller to the label . . .
● Follow the same steps as for the text field.
In the connection configuration dialog:
● Set the connection type to Outlet.
● Set the name to label.
● Set the type to UILabel.
Make the Text Field’s Delegate Connection
The text field sends a message to its delegate when the user taps the Return button in the keyboard. You
can use this callback to dismiss the keyboard (see “Configure the View Controller as the Text Field’s
Delegate” (page 49)).
To set the text field’s delegate . . .
1. In Xcode, select the view controller’s nib file (MyViewController.xib).
2. Control-click in the text field.
3. Using the translucent panel that appears, select the open circle after delegate and drag to the File’s
Owner.
Make the Text Field’s Delegate Connection 432011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 5
Configuring the View
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 44/64
Testing
You can now test the application.
To test the application . . .
● Click Run.
Make sure that all the files are saved.
You should find that the button works (it highlights when you tap it). You should also find that if you touchin the text field, the keyboard appears and you enter text. There is, however, no way to dismiss the keyboard.
To do that, you have to implement the relevant delegate method. You’ll do that in the next chapter.
44 Testing2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 5
Configuring the View
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 45/64
Recap
You configured the nib file with appropriate connections; in doing so, you also updated the header and
implementation files to support the outlets and action.
There’s noneedto use the Xcode feature toaddthe source code at thesametime as establishing a connection;
you canadd thepropertyand method declarations to the header file yourself, and then make theconnections
like you did with the text field’s delegate. Typically, though, you make fewer mistakes (and have less typing
to do) if you let the tools do as much of the work as they can.
Recap 452011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 5
Configuring the View
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 46/64
46 Recap2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 5
Configuring the View
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 47/64
There are several parts to implementing the view controller. You need to add a property for the user’s name
including memory management, implement the changeGreeting:method, and ensure that the keyboard
is dismissed when the user taps Done.
The User’s Name Property
You then need to add a property for the user’s name, which is a string. You add the property declaration to
the view controller’s header file (MyViewController.h).
To add a property declaration for the user’s name . . .
● Add a @property statement for a string called userName.
The property declaration looks like this.
@property (nonatomic, copy) NSString *userName;
Your interface file should look similar to this:
#import <UIKit/UIKit.h>
@interface MyViewController : UIViewController <UITextFieldDelegate> {
UITextField *textField;
UILabel *label;
NSString *userName;
}
@property (nonatomic, retain) IBOutlet UITextField *textField;
@property (nonatomic, retain) IBOutlet UILabel *label;
@property (nonatomic, copy) NSString *userName;
- (IBAction)changeGreeting:(id)sender;
@end
To complete the implementation, you also need to tell the compiler to synthesize the accessor methods, and
update the dealloc method. You add the implementation parts to the view controller’s implementation
file (MyViewController.m).
The User’s Name Property 472011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 6
Implementing the View Controller
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 48/64
To synthesize the accessor methods for user name property . . .
● Synthesize the userName property by adding the following after the @implementation
MyViewController line:
@synthesize userName;
This tells the compiler to synthesize accessor methods for these property according to the specification you
gave in the interface file. The declaration of the userName property is @property (nonatomic, copy)
NSString *userName;), so the compiler generates two accessor methods: - (NSString *)userName
and - (void)setUserName:(NSString *)newUserName. In the setUserName:method a copy is made
of the string that’s passed in. This is useful to ensure encapsulation (the passed-in string might be
mutable—you want to make sure that the controller maintains its own copy). For more about encapsulation,
see “Mechanisms Of Abstraction” in Object-Oriented Programming with Objective-C .
You must relinquish ownership in the dealloc method because the property declaration specifies that the
view controller owns the instance variables (retain and copy imply ownership; see “Memory Management
Rules” in Memory Management Programming Guide).
To correctly handle memory management for the user name property in dealloc . . .
● In the dealloc method, release userName by adding the following before the invocation of super:
[userName release];
The completed dealloc method to should look similar to this:
- (void)dealloc {
[textField release];
[label release];
[userName release];
[super dealloc];
}
The changeGreeting: Method
When a button is tapped, it sends a changeGreeting:message to the view controller. The view controller
then should retrieve the string from the text field and update the label appropriately. Thus, the
changeGreeting: method should:
1. Retrieve the text from the text field and set the controller’s userName property to the result.
2. Create a new string, based on the userName property, to display in the label.
48 The changeGreeting: Method2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 6
Implementing the View Controller
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 49/64
To implement the changeGreeting: method . . .
1. In Xcode, display MyViewController.m in the source editor.
2. Complete the implementation of the changeGreeting: method.
- (IBAction)changeGreeting:(id)sender {
self.userName = textField.text;
NSString *nameString = self.userName;
if ([nameString length] == 0) {
nameString = @"World";
}
NSString *greeting = [[NSString alloc] initWithFormat:@"Hello, %@!",
nameString];
label.text = greeting;
[greeting release];
}
There are several new pieces to this method:
● self.userName = textField.text; retrieves the text from the text field and sets the controller’s
userName property to the result.
In this case, you don’t actually use the user name anywhere else, but it ’s important to understand its
role. It’s the very simple model object that the view controller is managing. In general, the controller
should maintain informationabout applicationdata in its ownmodel objects—application datashouldn’t
be stored in user interface elements.
● @"World" is a string constant represented by an instance of NSString.
● The initWithFormat: method creates a new string that follows the format specified by the format
string, like the printf function.
%@ indicatesthat a string object shouldbe substituted. To learn more about strings, seeStringProgramming
Guide.
Configure the View Controller as the Text Field’s Delegate
If you build and run the application, you should findthat if you tap the button, the label shows “Hello, World!”
If you select the text field and start typing, though, you should find that you have no way to indicate that
you’ve finished entering text and dismiss the keyboard.
Configure the View Controller as the Text Field’s Delegate 492011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 6
Implementing the View Controller
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 50/64
In an iOS application, the keyboard is shown automatically when an element that allows text entry becomes
the first responder; it is dismissedautomatically when theelement loses first responder status. (You can learn
more about first responder by reading “The Event-Handling System” in iOS Application Programming Guide.)
There’s no way to directly message the keyboard; you can, however, make it appear or disappear as a
side-effect of toggling the first responder status of a text-entry element.
The UITextFieldDelegate protocol includes a method, textFieldShouldReturn:, that the text field
calls whenever the user taps the Return button (whatever text the button shows). Because you set the view
controller as the text field’s delegate, you can implement this method to force the text field to lose first
responder statusbysending it theresignFirstRespondermessage—which has the side-effect of dismissing
the keyboard.
Theview controller must adopt theUITextFieldDelegateprotocol. To specifythata class adopts a protocol,
in the interface add the name of the protocol in angle brackets (<>) after the name of the class from which
your class inherits.
To implement MyViewController as the text field’s delegate . . .
1. In the view controller’s header file (MyViewController.h), add <UITextFieldDelegate> after
UIViewController.
The interface declaration should look like this:
@interface MyViewController : UIViewController <UITextFieldDelegate> {
This declaration specifies that the view controller class adopts the UITextFieldDelegate protocol.
2. In the view controller’s implementation file (MyViewController.m), implement the
textFieldShouldReturn:method.
The method should tell the text field to resign first responder status. The implementation might look like this:
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
if (theTextField == textField) {
[textField resignFirstResponder];
}
return YES;
}
In this application, it’s not really necessary to include the theTextField == textField test since
there’s only one text field. It’s worth pointing out the pattern, though, since there may be occasions
when your object is the delegate of more than one object of the same type and you may need to
differentiate between them.
Test the Application
Build and run the application; it should behave as you expect. (Tap Done to dismiss the keyboard when you
have entered your name, then tap the Hello button to display “Hello, <Your Name>!” in the label.)
50 Test the Application2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 6
Implementing the View Controller
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 51/64
If the application doesn’t behave as you expect, you need to troubleshoot (see “Troubleshooting” (page 53)).
Recap
You finished the implementation of the view controller and so completed your first iOS application.
Congratulations.
Take a moment to think about how the view controller fits into the overall application architecture. You will
use view controllers in all iOS applications you write.
Then take a break, and start to think about what you should do next.
Recap 512011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 6
Implementing the View Controller
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 52/64
52 Recap2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 6
Implementing the View Controller
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 53/64
This section describes some approaches to solving common problems that you may encounter.
Code and Compiler Warnings
If things aren’t working as they should, first compare your code with the complete listings as given in “Code
Listings” (page 59).
Your code should compile without any warnings. Objective-C is a very flexible language, and so sometimes
the most you get from the compiler is a warning. Typically you should treat warnings as very likely to beerrors.
Check the Nib Files
As a developer, if things don’t work correctly, your natural instinct is to check your source for bugs. Cocoa
adds another dimension. Much of your application’s configuration may be “encoded” in the nib files. And if
you haven’t made the correct connections, then your application won’t behave as you expect.
● If your user interface doesn’t reflect changes you made to the nib file, make sure you saved the nib file
before you built the project.
● If the text doesn’t update when you tap the button, it might be that you didn’t connect the button’s
action to the view controller, or connect the view controller’s outlets to the text field or label.
● If the keyboard does not disappear when you tap Done, you may not have connected the text field’s
delegateor connected the view controller’s textFieldoutlet to the text field (see “Makethe Text Field’s
Delegate Connection” (page 43)). If you have connected the delegate, there may be a more subtle
problem (see “Delegate Method Names” (page 53)).
Delegate Method Names
A common mistake with delegates is to misspell the delegate method name. Even if you’ve set the delegate
object correctly, if the delegate doesn’t implement the method with exactly the right name, it won’t be
invoked. It ’s usually best to copy and paste delegate method declarations from the documentation.
Code and Compiler Warnings 532011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 7
Troubleshooting
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 54/64
54 Delegate Method Names2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 7
Troubleshooting
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 55/64
This chapter suggests directions you might take next in learning about iOS development.
Improve the User Interface
In thistutorial, youcreated a verysimple iOS application. Cocoa Touchoffers a richdevelopment environment,
though, and you’ve only scratched the surface. From here, you should explore further. Start with this
application. As noted in the first chapter, the user interface is critical to a successful iOS application. Try to
improve the user interface. Add images and color to the elements. Add a background image and an icon for
the application. Look at the inspectors in Interface Builder to see how else you can configure elements.
Many iPhone applicationssupport multiple orientations; applications for iPad should support all orientations.
Make sure the view controller supports multiple orientations (see the
shouldAutorotateToInterfaceOrientation:method), then (in Interface Builder) adjust your user
interface to make sure that all the user interface elements are properly positioned if the view is rotated.
Create User Interface Elements Programmatically
In thetutorial, you created the user interface using InterfaceBuilder. InterfaceBuilder allows you to assemble
user interface components quickly and easily. Sometimes, however, you may want—or need—to create userinterface elements in code (for example, if you create a custom table view cell you typically create and lay
out the subviews programmatically).
First, open the MyViewController nib file and remove the text field from view.
If you want to create the entire view hierarchy for a view controller in code, you override loadView. In this
case, however, you want to load the nib file then perform additional configuration (add another view). You
therefore override viewDidLoad instead. (The viewDidLoad method gives you a common override point
you can use whether you load the main view using a nib file or by overriding loadView.)
In MyViewController.m, add the following implementation of viewDidLoad:
- (void)viewDidLoad {
CGRect frame = CGRectMake(20.0, 68.0, 280.0, 31.0);
UITextField *aTextField = [[UITextField alloc] initWithFrame:frame];
self.textField = aTextField;
[aTextField release];
textField.textAlignment = UITextAlignmentCenter;
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.autocapitalizationType = UITextAutocapitalizationTypeWords;
Improve the User Interface 552011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 8
Next Steps
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 56/64
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.delegate = self;
[self.view addSubview:textField];
}
Notice that there’s quite a lot of code compared with how easy it was to create and configure the text fieldin Xcode.
In the application delegate, create the view controller instance using alloc and init instead of alloc and
initWithNibName:bundle:
Build and run the application. Make sure it behaves as it did before.
Install the Application on a Device
If you have a suitable device connected to your computer via its 30-pin USB cable, and you have a validcertificate from the iOS Developer Program, set the active SDK for your project to “iPhone Device” (instead
of “iOS Simulator”) and build and run the project. Assuming your code compiles successfully, Xcode then
automatically uploads your application to your device. For more details, see iOS Development Guide.
Add More Functionality
Next you can try expanding on the functionality. There are many directions in which you can go:
● Write a custom view. Rather than using a view as a canvas on which to drop prebuilt user interface
controls, you might try writing a custom view that draws its own content or responds to touch events.
For inspiration, look at examples such as MoveMe and Metronome.
● Use a table view. Although you used Xcode to layout the user interface for this application, many
applications actually use table views to lay out the interface. This makes it easy to create an interface
that extends beyond the bounds of the screen—allowing the user to easily scroll to reveal additional
elements. You should first investigate how to create a simple list using a table view. There are several
sample code projects that you can look at—including TableViewSuite—then you can create your own.
● Use a navigation controller. Navigation controllers and tab bar controllers provide an architecture that
allow you to create drill-down style interfaces and let the user select different views in your application.
Navigation controllers often work in conjunction with table views, but both navigation controllers and
tab bar controllers work together with view controllers. Have a look at some of the sample
applications—such as SimpleDrillDown—that use navigation controllers and expand on them to create
your own applications.
● Localize your app. You can often increase the size of your potential marketplace by localizing your
application. Internationalization is the process of making your application localizable. To learn more
about internationalization, read Internationalization Programming Topics.
● Optimize your code. Performance is critical to good user experience on iOS. You should learn to use
the various performance tools provided with Mac OS X—in particular Instruments—to tune your
application so that it minimizes its resource requirements.
56 Install the Application on a Device2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 8
Next Steps
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 57/64
The most important thing is to try out new ideas and to experiment—there are many code samples you can
look at for inspiration, and the documentation will help you to understand concepts and programming
interfaces.
Add Unit Tests
When you created the project, you didn’t select the option to add support for unit tests. Testing, however,
is an important aspect of best practices for Cocoa development. In some respects you can understand it as
the counterpart of the design principle of encapsulation—it ensures that if the implementation of a method
changes, it still works as advertised. Consider now adding suppor for unit testing. You can either create a
new version of the tutorial that sets up unit testing, or using the current project in Xcode choose File > New
> New Target then select Other > Cocoa Unit Testing Bundle. Look to see what Xcode adds to the project.
To learn about unit testing, see “Unit Testing Applications”.
Add Unit Tests 572011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 8
Next Steps
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 58/64
58 Add Unit Tests2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
CHAPTER 8
Next Steps
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 59/64
This appendix provides listings for the two classes you define. The listings don’t show comments and other
method implementations from the file templates.
HelloWorldAppDelegate
The header file: HelloWorldAppDelegate.h
#import <UIKit/UIKit.h>
@class MyViewController;
@interface HelloWorldAppDelegate : NSObject <UIApplicationDelegate> {
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) MyViewController *myViewController;
@end
The implementation file: HelloWorldAppDelegate.m#import "MyViewController.h"
#import "HelloWorldAppDelegate.h"
@implementation HelloWorldAppDelegate
@synthesize window=_window;
@synthesize myViewController=_myViewController;
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
MyViewController *aViewController = [[MyViewController alloc]initWithNibName:@"MyViewController" bundle:[NSBundle mainBundle]];
[self setMyViewController:aViewController];
[aViewController release];
self.window.rootViewController = self.myViewController;
[self.window makeKeyAndVisible];
return YES;
}
HelloWorldAppDelegate 592011-03-08 | © 2011 Apple Inc. All Rights Reserved.
APPENDIX A
Code Listings
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 60/64
// Other methods from the template omitted
- (void)dealloc {
[_myViewController release];
[_window release];
[super dealloc];}
@end
MyViewController
The header file: MyViewController.h
#import <UIKit/UIKit.h>
@interface MyViewController : UIViewController <UITextFieldDelegate> {
UITextField *textField;
UILabel *label;
NSString *userName;
}
@property (nonatomic, retain) IBOutlet UITextField *textField;
@property (nonatomic, retain) IBOutlet UILabel *label;
@property (nonatomic, copy) NSString *userName;
- (IBAction)changeGreeting:(id)sender;
@end
The implementation file: MyViewController.m
#import "MyViewController.h"
@implementation MyViewController
@synthesize textField;
@synthesize label;
@synthesize userName;
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
if (theTextField == textField) {
[textField resignFirstResponder];
}
return YES;
}
- (void)dealloc {
[textField release];
[label release];
60 MyViewController2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
APPENDIX A
Code Listings
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 61/64
[userName release];
[super dealloc];
}
- (IBAction)changeGreeting:(id)sender {
self.userName = textField.text;
NSString *nameString = self.userName;
if ([nameString length] == 0) {
nameString = @"World";
}
NSString *greeting = [[NSString alloc] initWithFormat:@"Hello, %@!",
nameString];
label.text = greeting;
[greeting release];
}
// Other methods from the template omitted.
@end
MyViewController 612011-03-08 | © 2011 Apple Inc. All Rights Reserved.
APPENDIX A
Code Listings
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 62/64
62 MyViewController2011-03-08 | © 2011 Apple Inc. All Rights Reserved.
APPENDIX A
Code Listings
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 63/64
This table describes the changes to Your First iOS Application.
NotesDate
Updated for Xcode 4.2011-03-08
Corrected a bad link.2010-10-12
Updated for iOS 4.2010-07-01
Updated for iOS 3.2.2010-03-15
Emphasized need to connect text field in Interface Builder.2009-10-08
Removed a reference todotsyntax for an example that used an accessor method
directly.
2009-08-10
Updated for iOS 3.0.2009-06-15
Corrected typographical errors.2009-01-06
Clarified description of the target-action design pattern.2008-10-15
Minor corrections and clarifications.2008-09-09
New document that introduces application development for iPhone.2008-06-09
632011-03-08 | © 2011 Apple Inc. All Rights Reserved.
REVISION HISTORY
Document Revision History
8/6/2019 00-Your First iPhone OS Application
http://slidepdf.com/reader/full/00-your-first-iphone-os-application 64/64
REVISION HISTORY
Document Revision History