Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
General
2011-10-12
Apple Inc. 2011 Apple Inc. All rights reserved. No part of this publication may be 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 Apples copyright notice. The Apple logo is a trademark of Apple Inc. No licenses, express or implied, are granted with respect to any of the technology described in this document. Apple retains all intellectual property rights associated with the 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, iTunes, Mac, Mac OS, 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 Cisco in the U.S. and other countries and is used under license.
Even though Apple has reviewed this document, APPLE MAKES NO WARRANTY OR REPRESENTATION, EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS DOCUMENT, ITS QUALITY, ACCURACY, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. AS A RESULT, THIS DOCUMENT IS PROVIDED AS IS, AND YOU, THE READER, ARE ASSUMING THE ENTIRE RISK AS TO ITS QUALITY AND ACCURACY. IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES RESULTING FROM ANY DEFECT OR INACCURACY IN THIS DOCUMENT, even if advised of the possibility of such damages. THE WARRANTY AND REMEDIES SET FORTH ABOVE ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL OR WRITTEN, EXPRESS OR IMPLIED. No Apple dealer, agent, or employee is authorized to make
any modification, extension, or addition to this warranty. Some states do not allow the exclusion or limitation of implied warranties or liability for incidental or consequential damages, so the above limitation or exclusion may not apply to you. This warranty gives you specific legal rights, and you may also have other rights which vary from state to state.
Contents
Introduction
Chapter 1
Getting Started 9
Create and Test a New Project 9 Find Out How an Application Starts Up 15 Recap 20
Chapter 2
Chapter 3
Chapter 4
Chapter 5
3
2011-10-12 | 2011 Apple Inc. All Rights Reserved.
CONTENTS
Configure the View Controller as the Text Fields Delegate 50 Test the Application 51 Recap 51 Chapter 6
Troubleshooting 53
Code and Compiler Warnings 53 Check the Storyboard File 53 Delegate Method Names 53
Chapter 7
Next Steps 55
Improve the User Interface 55 Install the Application on a Device 55 Add More Functionality 55 Add Unit Tests 56
Appendix A
Code Listings 57
The Interface file: HelloWorldViewController.h 57 The Implementation File: HelloWorldViewController.m 57
4
2011-10-12 | 2011 Apple Inc. All Rights Reserved.
INTRODUCTION
Your First iOS Application introduces you to the Three Ts of iOS app development:
Tools. How to use Xcode to create and manage a project. Technologies. How to create an application that responds to user input. Techniques. How to take advantage of the fundamental design patterns that underlie all iOS app development.
After you complete all the steps in this tutorial, youll have an app that accepts your input and prints it on the screen:
5
2011-10-12 | 2011 Apple Inc. All Rights Reserved.
INTRODUCTION
To benefit from this tutorial, you must already have some familiarity with the basics of computer programming in general and with the Objective-C language in particular. If you havent used Objective-C before, read Learning Objective-C: A Primer before you begin this tutorial. Note: You can use this tutorial to get started with iOS app development even if you intend to develop solely for iPad. Although this tutorial shows the iPhone user interface, the tools and techniques you use are exactly the same as those you use to develop iPad applications.
At a Glance
Following this tutorial helps you get started on the path to developing great iOS apps. Although the app you create in this tutorial is very simple, it will help you get comfortable with the iOS development environment and introduce you to the powerful design patterns that characterize the best iOS apps.
At a Glance
2011-10-12 | 2011 Apple Inc. All Rights Reserved.
INTRODUCTION
See Also
Developing an iOS app is a multistep process that ranges from determining what the app should do to submitting it to the App Store. Your First iOS Application cant help you decide what your apps should do, and it doesnt describe how to submit them to the App Store, but there are many resources that can help you accomplish these and other tasks. Some of these resources are listed here:
To learn about the recommended approaches to designing the user interface and user experience of an iOS app, see iOS Human Interface Guidelines. For comprehensive guidance on creating a full-featured iOS app, see iOS App Programming Guide. To learn about all the tasks you need to perform as you prepare to submit your app to the App Store, see App Development Overview.
See Also
2011-10-12 | 2011 Apple Inc. All Rights Reserved.
INTRODUCTION
See Also
2011-10-12 | 2011 Apple Inc. All Rights Reserved.
CHAPTER 1
Getting Started
To create the iOS application in this tutorial, you need Xcode 4.2. Xcode is Apples integrated development environment (or IDE) for both iOS and Mac OS X development. When you install Xcode on your Mac, you also get the iOS SDK, which includes the programming interfaces of the iOS platform. If you dont have Xcode installed on your Mac, visit the iOS Dev Center and download the Xcode 4.2 developer toolset (which includes the iOS 5 SDK). Double-click the package and follow the installer instructions.
CHAPTER 1
Getting Started
If youve created or opened a project in Xcode before, you might see a project window instead of the Welcome to Xcode window. 2. In the Welcome to Xcode window, click Create a new Xcode project (or choose File > New > New project). Xcode opens a new window and displays a dialog in which you can choose a template. Xcode includes several built-in application templates that you can use to develop common styles of iOS apps. For example, the Tabbed template creates an app that is similar to iTunes and the Master-Detail template creates an app that is similar to Mail.
10
CHAPTER 1
Getting Started
3. 4.
In the iOS section at the left side of the dialog, select Application. In the main area of the dialog, select Single View Application and then click Next. A new dialog appears that prompts you to name your application and choose additional options for your project.
11
CHAPTER 1
Getting Started
5.
Fill in the Product Name, Company Identifier, and Class Prefix fields. You can use the following values:
Product Name: HelloWorld Company Identifier: Your company identifier, if you have one. If you dont have a company identifier, you can use edu.self. Class Prefix: HelloWorld
Note: Xcode uses the product name you entered to name your project and the application. Xcode uses the class prefix name you entered to name the classes it creates for you. For example, Xcode automatically creates an application delegate class and names it HelloWorldAppDelegate. If you enter a different value for the class prefix, then the application delegate class is named YourClassPrefixNameAppDelegate. To keep things simple, this tutorial assumes that you named your product HelloWorld and that you used HelloWorld for the class prefix value. 6. 7. In the Device Family pop-up menu, make sure that iPhone is selected. Make sure that the Use Storyboard and Use Automatic Reference Counting options are selected and that the Include Unit Tests option is unselected (these are the default values).
12
CHAPTER 1
Getting Started
8.
Click Next. Another dialog appears that allows you to specify where to save your project.
9.
Specify a location for your project (leave the Source Control option unselected) and then click Create. You should see a new project window similar to this:
Even though you havent yet written any code, you can build your application and run it in the Simulator application that is included in Xcode. As its name implies, Simulator allows you to get an idea of how your app would look and behave if it were running on an iOS-based device.
13
CHAPTER 1
Getting Started
After Xcode finishes building your project, Simulator should start automatically. Because you specified an iPhone product (as opposed to an iPad product), Simulator displays a window that looks like an iPhone. On the simulated iPhone screen, Simulator opens your application, which should look like this:
14
CHAPTER 1
Getting Started
Right now, your application is not very interesting: it simply displays a blank white screen. To understand where the white screen comes from, you need to learn about the objects in your code and how they work together to start the app. For now, quit Simulator (make sure you dont quit Xcode).
15
CHAPTER 1
Getting Started
The main function in main.m calls the UIApplicationMain function within an autorelease pool:
@autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([HelloWorldAppDelegate class])); }
The @autoreleasepool statement supports the Automatic Reference Counting (ARC) system. ARC provides automatic object-lifetime management for your application, ensuring that objects remain in existence for as long as they're needed and no longer. The call to UIApplicationMain creates an instance of UIApplication and an instance of the application delegate (in this case, HelloWorldAppDelegate). The main function of the app delegate is to provide the window into which your apps content is drawn. The call to UIApplicationMain also scans the applications Info.plist file. The Info.plist file is a property list that contains information about the application such as its name and icon. Find Out How an Application Starts Up
2011-10-12 | 2011 Apple Inc. All Rights Reserved.
16
CHAPTER 1
Getting Started
In the Supporting Files folder in the project navigator, select HelloWorld-Info.plist. Xcode opens the Info.plist file in the main editor area of the window, which should look similar to this:
Because you chose to use a storyboard in this project, the Info.plist file also contains the name of the storyboard file that the application object should load. A storyboard file contains an archive of the objects, transitions, and connections that define an applications user interface. To minimize distractions, close the Supporting Files folder in the project navigator by again clicking the disclosure triangle next to it. In this application, the storyboard file is named MainStoryboard.storyboard (note that the Info.plist file shows only the first part of this name). When the app starts, the MainStoryboard.storyboard file is loaded and the initial view controller is instantiated from it.
17
CHAPTER 1
Getting Started
Select MainStoryboard.storyboard in the project navigator. Xcode opens the storyboard file in the editor area. (The area behind the storyboard objectsthat is, the area that looks like graph paperis called the canvas.)
When you open the default storyboard file, your project window should look similar to this:
A storyboard file contains scenes and segues. A scene represents a view controller, which manages one area of content, and a segue represents a transition between two scenes.
18
CHAPTER 1
Getting Started
Because the Single View template provides only one area of content which occupies the entire screen, the MainStoryboard file in your app contains only one scene and no segues. (The arrow that points to the left side of the scene on the canvas is the initial scene indicator, which identifies the initial scene in an app.) The scene that you see on the canvas is named Hello World View Controller Scene because it is managed by the HelloWorldViewController object in your application. The Hello World View Controller scene consists of a few items that are displayed in the Xcode outline view (which is the pane that appears between the canvas and the project navigator):
A first responder placeholder object (represented by an orange cube). The first responder is a dynamic placeholder that represents the responder object that first receives events such as keyboard events, motion events, and action messages (youll learn more about action messages in The Target-Action Pattern Enables Responses to User Interactions (page 22)). You wont be doing anything with the first responder in this tutorial, but you can learn more about it in Event Handling Guide for iOS.
The HelloWorldViewController object (represented by a pale rectangle inside a yellow sphere). When a scene in a storyboard file is loaded, it creates an instance of the view controller class that manages it.
A view (which is listed below the view controlleryou might have to open the disclosure triangle next to HelloWorldViewController to reveal it). The white background of this view is what you saw when you ran the application in Simulator.
Note: The area below the scene on the canvas is called the scene dock. Right now, it displays the view controllers name (that is, Hello World View Controller). At other times, the scene dock can contain the icons that represent the first responder and the view controller object. During setup, the application object performs the following tasks:
Loads the main storyboard file. Gets the window object from the app delegate (or creates a new instance of UIWindow and associates it with the app delegate). Instantiates the storyboards initial view controller and assigns it as the window objects root view controller.
When the application object has completed these tasks, it sends its delegate an application:didFinishLaunchingWithOptions: message. This message gives the delegate an opportunity to perform other tasks, such as additional configuration, before the application is displayed. In this tutorial, the application delegate is provided by the Single View template and its called HelloWorldAppDelegate. You will not be changing the default app delegate class in this project, but you will be using delegation in a later step. You can learn more about delegation in Delegation Helps You Add Functionality Without Subclassing (page 21).
19
CHAPTER 1
Getting Started
Recap
In this chapter you used Xcode to create a new project based on the Single View template. Then, you built and ran the default application that the template defines. You also looked at some of the basic pieces of the project, such as the main.m source file, the Info.plist file, and the storyboard file, and learned how an application starts up. In the next chapter, youll learn about the design patterns that pervade iOS application development and how they apply to your app.
20
Recap
2011-10-12 | 2011 Apple Inc. All Rights Reserved.
CHAPTER 2
Before you start customizing your app, take a moment to learn about the programming environment youre working in and the design patterns that characterize great iOS applications. You can complete the tutorial without reading this chapter, but if you allow some time to read and think about the concepts it describes, youll have a much better understanding of iOS app development.
Cocoa Touch Provides the Frameworks You Need for iOS App Development
Cocoa Touch is the application environment for all iOS apps (Cocoa provides the application environment for Mac OS X apps). As you develop apps for iOS, including the app in this tutorial, youll rely on the object-oriented frameworks that Cocoa Touch provides. In particular, youll use the application programming interfaces (APIs) of the UIKit framework, which provides all the classes that an app needs to construct and manage its user interface. There are several resources that can help you gain a deeper understanding of Cocoa Touch (and Cocoa). A good place to start is Cocoa Fundamentals Guide.
Every iOS app must have an application delegate object; in this app, its an instance of the HelloWorldAppDelegate class thats provided by the Single View template.
Cocoa Touch Provides the Frameworks You Need for iOS App Development
2011-10-12 | 2011 Apple Inc. All Rights Reserved.
21
CHAPTER 2
In addition to performing custom configuration tasks, the app delegate can handle application-level events because it participates in the responder chain. In this tutorial, you do not have to perform custom configuration tasks or explicitly handle app-level events, so you do not need to make any changes to the HelloWorldAppDelegate source files.
The text field that youll be adding later needs to tell its delegate when the user is finished typing. To help accomplish this, you ensure that the view controller object (that is, HelloWorldViewController) conforms to the UITextFieldDelegate protocol.
22
CHAPTER 2
23
CHAPTER 2
24
CHAPTER 3
As you learned earlier, a view controller is responsible for managing one scene, which represents one area of content. The content that you see in this area is defined in the view controllers view. In this chapter, you take a closer look at your view controller and learn how to adjust the background color of the view.
2.
25
CHAPTER 3
Note that the scene and the scene dock are both outlined in blue, and the view controller object is selected in the scene dock. 3. 4. Click the rightmost View control in the toolbar to display the utilities area at the right side of the window. Click the Attributes inspector button at the top of the utilities area (its the fourth button from the left and it looks like this: ).
Your project window should look something like this (you might have to resize the Xcode window to see everything):
26
CHAPTER 3
In the Attributes inspector, you can see that the option Initial Scene Is Initial View is selected. Note that if you deselect this option, the initial scene indicator disappears from the canvas. For this tutorial, make sure the Initial Scene option remains selected.
27
CHAPTER 3
28
CHAPTER 3
Note that because Xcode highlighted the view when you selected it, the color on the canvas might look different from the color in the Colors window. 5. Close the Colors window.
Test your application in Simulator. You should see something like this:
29
CHAPTER 3
Tip You dont have to save your work before you run your app because when you click Run (or choose Project > Run), Xcode automatically saves the files to which youve made changes.
Before you continue with the tutorial, restore the views background color to white.
30
CHAPTER 3
After youve verified that your app again displays a white background, quit Simulator. When you run your app, Xcode might open the Debug area at the bottom of the project window. You wont use this pane in this tutorial, so you can close it to make more room in your window.
The Debug View button is the middle View button and it looks like this:
Recap
In this chapter, you inspected the scene and changed (and restored) the background color of the view. In the next chapter, you add controls to the view.
Recap
2011-10-12 | 2011 Apple Inc. All Rights Reserved.
31
CHAPTER 3
32
Recap
2011-10-12 | 2011 Apple Inc. All Rights Reserved.
CHAPTER 4
Xcode provides a library of objects that you can add to a storyboard file. Some of these are user interface elements that belong in a view, such as buttons and text fields; others are higher level objects, such as view controllers and gesture recognizers. Your Hello World View Controller scene already contains a viewnow you need to add a button, a label, and a text field. Then, you make connections between these elements and the view controller class so that the elements provide the behavior you want.
To add the UI elements to the view and lay them out appropriately . . .
1. If necessary, select MainStoryboard.storyboard in the project navigator to display the scene on the canvas. If necessary, open the object library. The object library appears at the bottom of the utilities area. If you dont see it, you can click the object library button, which looks like this: 3. .
2.
In the object library, choose Controls from the Objects pop-up menu. Xcode displays a list of controls below the pop-up menu. The list displays each controls name and appearance, and a short description of its function.
4.
One at a time, drag a text field, a round rect button, and a label from the list to the view.
33
CHAPTER 4
5.
In the view, lay out the UI elements appropriately. As you move UI elements within the view, dashed blue lines appear that help you align the items with the edges of the view and with each other. (These dashed blue lines are called alignment guides.) You can also resize the UI elements by dragging their resize handles. To reveal an elements resize handles, select it (that is, click it once). You can lay out your apps user interface any way you choose, but this tutorial uses the following layout:
34
CHAPTER 4
6.
In the view, select the text field and then in the Placeholder field of the Text Field Attributes inspector enter the phrase Your Name. In the Text Field Attributes inspector, click the middle Alignment button to center the text fields text. In the Label Attributes inspector, click the middle Alignment button to center the labels text. In the view, double-click the button and enter the text Hello.
7. 8. 9.
After you add the text field, label, and button and make the other recommended changes, your project should look similar to this:
35
CHAPTER 4
There are a few other changes you can make to the text field so that it behaves as users expect. First, because users will be entering their names, you can ensure that iOS suggests capitalization for each word they type. Second, you can make sure that the keyboard associated with the text field is configured for entering names (rather than numbers, for example), and that the keyboard displays a Done button. This is the principle behind these changes: Because you know at design time what type of information a text field will contain, you can configure it so that its runtime appearance and behavior are well suited to the users task. You make all of these configuration changes in the Attributes inspector.
36
CHAPTER 4
2.
In the Capitalization pop-up menu, choose Words. Ensure that the Keyboard pop-up menu is set to Default. In the Return Key pop-up menu, choose Done.
Run your app in Simulator to make sure that the UI elements you added look the way you expect them to. If you click the button, it should highlight, and if you click inside the text field, the keyboard should appear. At the moment, though, the button doesnt do anything, the label remains empty, and theres no way to dismiss the keyboard after it appears. To add this functionality, you need to make the appropriate connections between the UI elements and the view controller. These connections are described next. Note: When you run an app in Simulator, you have to click controls that users tap when they run your app on a device.
2.
The assistant editor button is the middle Editor button, which looks like this: 3.
Make sure that the Assistant displays the view controllers header file (HelloWorldViewController.h).
37
CHAPTER 4
4.
Control-drag from the button in the view to the method declaration area in the header file. As you Control-drag, you should see something like this:
When you release the Control-drag, Xcode displays a popover in which you can configure the action connection you just made:
38
CHAPTER 4
5.
In the Connection pop-up menu, choose Action. In the Name field, enter changeGreeting: (be sure to include the colon). Make sure that the Type field contains id. The id data type can represent any Cocoa object (to learn more about it, see The Dynamism of Objective-C in Cocoa Fundamentals Guide). You want to use id here because it doesnt matter what type of object sends the message.
Make sure that the Event pop-up menu contains Touch Up Inside. You specify the Touch Up Inside event because you want the message to be sent when the user lifts the finger inside the button. (Touch Up Inside corresponds to UIControlEventTouchUpInside.)
After you configure the action connection, the popover should look like this:
6.
In the popover, click Connect. Xcode adds a stub implementation of the new changeGreeting: method and indicates that the connection has been made by displaying a filled-in circle to the left of the method:
39
CHAPTER 4
When you Control-dragged from the button to the HelloWorldViewController.h file and configured the resulting action, you accomplished two things:
You added the appropriate code to the view controller class. Specifically, you added the following action method declaration to the header file:
- (IBAction)changeGreeting:(id)sender;
Note: IBAction is a special keyword that is used only to tell Xcode to treat a method as an action for target-action connections. IBAction is defined to void. The sender parameter in the action method refers to the object that is sending the action message (in this tutorial, the sender is the button).
You created a connection between the button and the view controller. Establishing the connection is the equivalent of invoking addTarget:action:forControlEvents: on the button, with the target being the view controller, the action being the changeGreeting: selector, and the control events containing UIControlEventTouchUpInside.
Next, you create connections between the view controller and the two remaining UI elements (that is, the label and the text field).
40
CHAPTER 4
2.
In the popover that appears when you release the Control-drag, configure the text fields connection:
Make sure that the Connection pop-up menu contains Outlet. In the Name field, enter textField. You can call the outlet whatever you want, but your code is more understandable when an outlet name bears some relationship to the item it represents.
41
CHAPTER 4
Make sure that the Type field contains UITextField. Setting the Type field to UITextField ensures that the outlet can only connect to a text field.
Make sure that the Storage pop-up menu contains Weak. The weak storage specifer is appropriate because the text field is a subview of the view controllers view object, and is therefore owned by the view.
After you make these settings, the popover should look like this:
3.
You accomplished two things by adding an outlet for the text field:
You added appropriate code to the view controller class. Specifically, you added the following declaration to the header file:
@property (weak, nonatomic) IBOutlet UITextField *textField;
Note: IBOutlet is a special keyword that is used only to tell Xcode to treat the object as an outlet. Its actually defined as nothing so it has no effect at compile time. To the viewDidUnload method you added:
textField = nil;
As its name suggests, the viewDidUnload method is called when your view is unloaded. The viewDidUnload method is also the appropriate place in which to set the view's outlets to nil. Its good programming practice to set to nil an object that no longer exists, because it allows other code to make sure that an object exists before attempting to use it.
You established a connection from the view controller to the text field. Establishing a connection from the view controller does the equivalent of invoking setTextField: on the view controller, passing the text field as the parameter.
42
CHAPTER 4
Now add an outlet for the label and configure the connection. The steps you follow for this task are the same as the ones you followed to add the outlet for the text field, but with appropriate changes to the configuration.
2.
Make sure that the Connection pop-up menu contains Outlet. In the Name field, enter label. Make sure that the Type field contains UILabel. Make sure that the Storage pop-up menu contains Weak.
3.
At this point in the tutorial, youve created a total of three connections to your view controller:
An action connection for the button An outlet connection for the text field An outlet connection for the label
The Standard editor button is to the left of the Assistant editor button, and it looks like this: 2. 3. 4. Click the Utilities view button to open the utilities area. Select Hello World View Controller in the outline view. Show the Connections inspector in the utilities area. The Connections inspector button is the rightmost inspector button, and it looks like this:
43
CHAPTER 4
In the Connections inspector, Xcode displays the connections for the selected object (in this case, the view controller). In your project window, you should see something like this:
Notice that theres a connection between the view controller and its view, in addition to the three connections you created. Xcode provides this default connection between the view controller and its view; you do not have to access it in any way.
44
CHAPTER 4
You need to specify a delegate object for the text field because the text field sends a message to its delegate when the user taps the Return button in the keyboard. In a later step, youll use the method associated with this message to dismiss the keyboard (see Configure the View Controller as the Text Fields Delegate (page 50)). Make sure that the storyboard file is open on the canvas. If its not, select MainStoryboard.storyboard in the project navigator.
45
CHAPTER 4
2.
Select delegate in the Outlets section of the translucent panel that appears.
Recap
When you configured the view with the appropriate connections you also updated the implementation file to support the outlets and the action. At this point in the tutorial, your HelloWorldViewController.m file should look similar to this (unchanged stub implementations are not shown):
#import "HelloWorldViewController.h" @implementation HelloWorldViewController @synthesize textField; @synthesize label; ... - (void)viewDidUnload { [self setTextField:nil]; [self setLabel:nil]; [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } ... - (IBAction)changeGreeting:(id)sender { } @end
Note that you dont have to use the Xcode feature that automatically adds code when you establish a connection by Control-dragging from the canvas to a source file. Instead, you can add the property and method declarations to the header file yourself, and then make the connections as you did with the text fields delegate. Typically, though, you make fewer mistakes (and have less typing to do) when you let Xcode do as much of the work as it can.
46
CHAPTER 5
There are several parts to implementing the view controller: You need to add a property for the users name, implement the changeGreeting: method, and ensure that the keyboard is dismissed when the user taps Done.
To add the variable and property declarations for the users name . . .
1. 2. In the project navigator, select HelloWorldViewController.h. Within the @interface braces, add a variable declaration for the string that will hold the users name. Note that you might have to enter the braces after the @interface statement. After you add the variable declaration, @interface block should look like this:
@interface HelloWorldViewController : UIViewController { NSString *userName; }
3.
After the closing @interface brace and before the @end statement, add an @property statement for the string variable you just declared. The property declaration looks like this:
@property (nonatomic, copy) NSString *userName;
The userName property needs a setter method called setUserName:. Youll provide this method in the next step.
47
CHAPTER 5
To complete the implementation of the userName property, you also need to tell the compiler to synthesize the accessor methods. You provide code to do this in the view controllers implementation file (that is, HelloWorldViewController.m).
When you use the @synthesize directive, you tell the compiler to synthesize accessor methods for a property according to the specification that you gave in the interface file. In this tutorial, your declaration of the userName property is @property (nonatomic, copy) NSString *userName;, so the compiler generates two accessor methods:
- (NSString *)userName - (void)setUserName:(NSString *)newUserName
By adding the underscore to userName in your @synthesize code line, you tell the compiler to use _userName as the name of the instance variable for the userName property. Because you didnt declare an instance variable called _userName in your class, this code line also asks the compiler to synthesize that as well. By convention, you prefix the instance variable name with an underscore to remind you that you shouldnt access an instance variable directly. Instead, you should use the accessor methods you synthesized. (An exception to this is that you can get and set an instance variable directly in an init method.) From an academic perspective, avoiding the direct access of instance variables helps preserve encapsulation, but there are also a couple of practical benefits:
Some Cocoa technologies (notably key-value coding) depend on the use of accessor methods, and on the appropriate naming of the accessor methods. If you dont 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 controllers view is a good example of a property value thats created on-demand.)
To help you remember this convention, modify the @synthesize code lines that Xcode added for the text field and label so that they look like this:
@synthesize textField=_textField; @synthesize label=_label;
(If youre interested, you can read more about encapsulation in Storing and Accessing Properties in Cocoa Fundamentals Guide.)
48
CHAPTER 5
self.userName = self.textField.text; retrieves the text from the text field and sets the view controllers userName property to the result.
In this tutorial, you dont actually use the string that holds the users name anywhere else, but its important to remember its role: Its the very simple model object that the view controller is managing. In general, the controller should maintain information about application data in its own model objectsapplication data shouldnt be stored in user interface elements.
NSString *nameString = self.userName; creates a new variable (of type NSString) and sets it to the view controllers userName property. @"World" is a string constant represented by an instance of NSString. If the user runs your app but does not enter any text (that is, [nameString length] == 0), nameString will contain the string
World .
49
CHAPTER 5
The initWithFormat: method creates a new string that follows the format specified by the format string (much like the C printf function with which you might be familiar). In the format string, %@ acts as a placeholder for a string object. All other characters within the double quotation marks of this format string will be displayed onscreen exactly as they appear. (To learn more about strings, see Strings.)
In this application, its not really necessary to include the theTextField == self.textField test because theres only one text field. This is a good pattern to use, though, because there may be occasions when your object is the delegate of more than one object of the same type and you might need to differentiate between them. 3. Select HelloWorldViewController.h in the project navigator.
50
CHAPTER 5
4.
In the @interface line, just before the opening brace, add <UITextFieldDelegate> after UIViewController. Your interface declaration should look like this:
@interface HelloWorldViewController : UIViewController <UITextFieldDelegate> { ...
This declaration specifies that your HelloWorldViewController class adopts the UITextFieldDelegate protocol.
Recap
Now that youve finished the implementation of the view controller, youve 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.
51
CHAPTER 5
52
Recap
2011-10-12 | 2011 Apple Inc. All Rights Reserved.
CHAPTER 6
Troubleshooting
If you have trouble getting your application to work correctly, try the problem-solving approaches described in this chapter.
If the text doesnt update when you click the button, it might be that you didnt connect the buttons action to the view controller, or that you didnt connect the view controllers outlets to the text field or label. If the keyboard does not disappear when you click Done, you might not have connected the text fields delegate or connected the view controllers textField outlet to the text field (see Make the Text Fields Delegate Connection (page 44)). If you have connected the delegate, there might be a more subtle problem (see Delegate Method Names (page 53)).
53
CHAPTER 6
Troubleshooting
54
CHAPTER 7
Next Steps
In this tutorial, you created a very simple iOS application. Cocoa Touch offers a rich development environment, though, and this tutorial only scratches the surface. This chapter suggests some directions you might take next as you continue to learn about iOS app development.
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 sample code projects such as MoveMe and Metronome.
55
CHAPTER 7
Next Steps
Use a table view. Although you used Xcode to lay out the user interface for this application, many applications use table views to lay out the interface. This makes it easy to create an interface that extends beyond the bounds of the screenallowing the user to 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, such as TableViewSuite, that you can use as a foundation for a custom app. Use a navigation controller. Navigation controllers and tab bar controllers provide different ways to organize an iOS app. Navigation controllers often work in conjunction with table views, but both navigation controllers and tab bar controllers work together with view controllers. Take a look at some of the sample code projectssuch as SimpleDrillDownthat use navigation controllers and expand on them to create your own applications. Localize your app. You can often increase the size of your potential market 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. High performance is critical to a good user experience on iOS. You should learn to use the various performance tools provided with Xcodein particular Instrumentsto tune your application so that it minimizes its resource requirements.
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.
56
APPENDIX A
Code Listings
This appendix provides listings for the interface and implementation files of the HelloWorldViewController class. The listings dont show comments and other method implementations from the file templates.
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField { if (theTextField == self.textField) { [theTextField resignFirstResponder]; } return YES; } - (IBAction)changeGreeting:(id)sender { self.userName = self.textField.text; NSString *nameString = self.userName; if ([nameString length] == 0) { nameString = @"World";
57
APPENDIX A
Code Listings
} NSString *greeting = [[NSString alloc] initWithFormat:@"Hello, %@!", nameString]; self.label.text = greeting; } @end
58
REVISION HISTORY
This table describes the changes to Your First iOS App. Date 2011-10-12 2011-06-06 2011-03-08 2010-10-12 2010-07-01 2010-03-15 2009-10-08 2009-08-10 Notes Updated to use storyboards and ARC. Corrected typographical errors. Updated for Xcode 4. Corrected a bad link. Updated for iOS 4. Updated for iOS 3.2. Emphasized need to connect text field in Interface Builder. Removed a reference to dot syntax for an example that used an accessor method directly. Updated for iOS 3.0. Corrected typographical errors. Clarified description of the target-action design pattern. Minor corrections and clarifications. New document that introduces application development for iPhone.
59
2011-10-12 | 2011 Apple Inc. All Rights Reserved.
REVISION HISTORY
60
2011-10-12 | 2011 Apple Inc. All Rights Reserved.