an action sheet for the iPhone-iPod Touch 67 Development Steps: Creating an Action Sheet for the an action sheet for the iPad 80 Development Steps: Creating an Action Sheet for the iPad
Trang 3introdUction xxiii
chaPter 1 Navigation 1
chaPter 2 Alerts, Action Sheets, and Modal Views 53
chaPter 3 Custom Table Views 1 2 1 chaPter 4 The Split View 1 37 chaPter 5 Touch Events 1 59 chaPter 6 Notification Processing 1 99 chaPter 7 Networking Concepts 227
chaPter 8 Multimedia 263
chaPter 9 Application Preferences 3 1 3 chaPter 10 Data Storage 339
chaPter 11 The Pasteboard 395
chaPter 12 Unit Testing 429
chaPter 13 Performance Tuning and Optimization 453
chaPter 14 Integrating iAds 469
chaPter 15 Multitasking 48 1 aPPendiX a Your Initial App — First Steps 505
aPPendiX B iPhone Developer Center 51 5 aPPendiX c Cocoa Touch Static Libraries 52 1 aPPendiX d Apple Developer Resources 543
indeX 547
Trang 5development
Trang 7development
Gene Backlin
Trang 8Indianapolis, IN 46256
www.wiley.com
Copyright © 2011 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with
respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose No warranty may be created or extended by sales or pro-motional materials The advice and strategies contained herein may not be suitable for every situation This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services
If professional assistance is required, the services of a competent professional person should be sought Neither the lisher nor the author shall be liable for damages arising herefrom The fact that an organization or Web site is referred to
pub-in this work as a citation and/or a potential source of further pub-information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read
For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002
Wiley also publishes its books in a variety of electronic formats Some content that appears in print may not be available
in electronic books
Library of Congress Control Number: 2010934751
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related trade dress are
trademarks or registered trademarks of John Wiley & Sons, Inc and/or its affiliates, in the United States and other tries, and may not be used without written permission iPhone and iPad are trademarks or registered trademarks of Apple, Inc All other trademarks are the property of their respective owners Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book
Trang 9Download from Wow! eBook <www.wowebook.com>
Trang 11Gene Backlin is owner and principal consultant of MariZack Consulting, formed
in 1991 with one purpose — to help He has been helping clients for over 30 years, including IBM, McDonnell Douglas, Waste Management, U.S Environmental Protection Agency, Nations Bank, Bank of America, and Bank One to name a few He is also a faculty member of DePaul University’s College of Computing and Digital Media.
His childhood interest in electronics helped him break into the computer industry
He still has the Heathkit H-8 digital computer and H-9 video terminal that he built
in 1978 He taught himself programming using Extended Benton Harbor Basic After the IBM-PC was introduced, Gene built the Heathkit H-151 PC-compatible computer, which is still running today If you ask him about the information revolution, his response would be “Fascinating.” He has devel- oped on computers that loaded programs from paper tape, to the revolutionary NeXT computer (he still has two), to the iPhone and iPad Gene feels very fortunate to have not only seen an industry evolve, but also to have been an active participant in it.
He is thrilled to have penned a companion text to his Developing NeXTSTEP Applications, which he wrote
back in 1995.
Trang 12daniel W meeks has been grep, awk and sed(ing) on Unix systems since Version 9 from Bell Labs and 2.8 BSD He was at Bell Labs in Naperville during the Cfront Version 1 days of C++ Since then he has been managing technology teams developing in C, Objective-C, C++, Java, and C# in various financial institu- tions and traveling the world in support of them Today he spends his weekends putting up infrastructure and develops mobile applications on Apple, Windows and Android as a hobby.
Trang 13eXecUtive editor
Carol Long
senior Project editor
Ami Frank Sullivan
Mary Beth Wakefield
freelancer editorial manaGer
Trang 15i WoUld first like to thank my wife Roseann, my son Zachary, and my daughter Marissa for putting
up with me while I was writing this book; and my son Ethan for keeping me young (remember what you are
to do if this idea ever comes up again).
I would also like to thank my mother Mary Louise and daughter Hannah Angel, for giving me the gift of themselves and their spirit, which I carry with me every day of my life I miss you.
To my father, who is there when I need him, and also has a really great name… thank you Gene!
To Helen and Jerry, you will never know how much you mean to me.
To Dan, I am glad we were able to share time together again after so many years.
This book is more than just words and code It is time and people The finished product you hold in your hand is a snapshot of events that somehow managed to come together with the very hard work of a lot of people; Carol, Ami, and Luann, I want to specifically thank you three for everything that you did
Finally I would like to once again thank Jean-Marc Krikorian for really doing nothing as he did the last time back in ’95.
I cannot forget you, the reader, for taking time out of your day to spend it with me This book was written for you, and I hope I have helped you in some way If you have any questions or comments, please let me know, thank you again!
Trang 17IntroductIon xxiii
naviGation
navigation stack 2 The navigation Bar 2
a simple navigation Bar 3
a simple Toolbar 18
a simple Tab Bar 26
a simple alertView for the iPhone-iPod Touch and iPad 54
Development Steps: Loading a File into a UITextView 55
Trang 18an action sheet for the iPhone-iPod Touch 67
Development Steps: Creating an Action Sheet for the
an action sheet for the iPad 80
Development Steps: Creating an Action Sheet for the iPad 81
a Modal View for the iPhone and iPod Touch 95
Development Steps: Creating a Modal View for the
a Modal View for the iPad 106
Development Steps: Creating a Modal View for the iPad 108
a Custom Table View application 122
Development Steps: A Custom Table View Application 122 Creating the Contacts plist Property List File 133
a simple split View application 138
Development Steps: A Simple Split View Application for the iPad 141 Creating the DataSource plist Property List File 145
Trang 19a simple Touch Handler 162
a simple Gesture recognizer 174
Development Steps: A Simple Gesture Recognizer 175
nsnotifications Concepts 200
a local named notification 201
a local Keyboard notification 211
Development Steps: A Local Keyboard Notification 212
Communication over a network 228
a simple network Browser 230
Peer-to-Peer Device Communications 244
Development Steps: Peer-to-Peer Device Communication 245
Trang 20Playing audio from the iPod library 265
Development Steps: Playing Audio from the iPod Library 266
an application That Plays Video from the iPod library 291
Development Steps: An Application That Plays Video from the iPod Library 292
application Configuration 313
setting simple Preferences 315
Source Code Listings for Setting Simple Preferences 320
Creating a Child Pane Preference Hierarchy 325
Development Steps: Creating a Child Pane Preference Hierarchy 326
Property lists 339
Trang 21The Common Premise for Data storage 343
Development Steps: A Simple Application Using Property Lists 344
Development Steps: A Simple Application Using Core Data 367
Cutting and Pasting Text 398
Cutting and Pasting images 407
Creating Custom Menus for the iPad 416
Development Steps: Creating Custom Menus for the iPad 418
setting Up the environment 429
a simple Unit Test 430
Unit Test Creation steps: a simple Unit Test 446
Trang 22a simple Memory leak Test 455
Development Steps Continued: Using the Instruments Application 467 Development Steps Continued: Using Build and Analyze
Joining the iad network 469
Preparing Your application to Use the iad network 470
a simple application Using iads 471
Development Steps: A Simple Application Using iAds 472
an application That Multitasks audio 483
Development Steps: An Application That Multitasks Audio 484
Xcode Project Builder 505
Trang 23interface Builder 512
resources for the ios 4 sDK 515
iPhone Developer Program 518
iTunes Connect 520 news & announcements 520
Xcode Project Template 521
Source Code Listings for the DataSource Static Library 523
an Xcode application Project 527
Trang 24iPhone Developer Program 543
iTunes app store 544 application Distribution Procedures 545 iTunes Connect Developer Guide 545
Trang 25in 1975 i PUrchased a Texas Instruments SR-56 pocket calculator What compelled me to purchase it was
the word programmable I didn’t quite know what that meant, but I knew I had to get it The SR-56 had 10
memories and 100 program steps After about a week tinkering with it, I started to understand the power of
a program I still have that calculator today, and while it no longer works, it is a reminder of how ing it is to write a program
fascinat-Over the decades, I worked with many technologies and languages, and over time, the development process was becoming routine The excitement that I originally felt with my SR-56 was beginning to fade That is, until 1989, and one word: NeXT The excitement had returned NeXT gave the developer a rich set of tools
to produce sophisticated applications within amazing time frames and with relative ease Developing ware just made sense now
soft-When this environment was introduced to the Mac platform, it was the beginning of a great relationship Today, there is the iPhone, iPod touch, and iPad For me, 35 years from the day I wrote my first program on
my SR-56, I am still like a kid in a candy store I wrote this book to give you a deeper insight into how you can use these tools to realize your ideas on these devices.
Who this Book is for
This book was written for the developer who is familiar with the Xcode environment and Objective-C guage in general
lan-For the reader who is familiar with developing applications but just not up to speed on Xcode and Objective C, please visit the Apple iPhone Dev Center at https://developer.apple.com/iphone/.
Each chapter discusses a specific topic or feature of the iPhone/iPad device Following the discussion, you will find the steps necessary to create a full working example of that feature The source code that you will develop is structured in a modular fashion, enabling you to extract it and implement the functionality in your own applications
What this Book covers
The topics covered in this book use the current SDK 4.0 for iPhone and iPod Touch, and the SDK 3.2 for the iPad Xcode and Interface Builder are the main tools used to create all the applications presented Finally, with the Instruments application, performance issues are discussed.
hoW this Book is strUctUred
Beginning with Chapter 1, the discussion will focus on the application frameworks included in the SDK, and through a step-by-step process, you will design applications that help you understand these frameworks, including when and where they are to be incorporated into your application In this book, you will learn by doing, and when you’ve completed all the Development Steps sections, you will have experience creating and adding functionality to iPhone and iPad applications using iOS 4 Topics include table views, image views, pickers, data storage, audio and video to name a few Finally, the book discusses procedures that will ensure your applications perform efficiently, allowing for a desirable user experience from those who purchase your applications from the Apple iTunes App Store.
Trang 26What yoU need to Use this Book
To write applications that will run on the iPhone or iPod Touch, you need to download the iPhone SDK 4.0 Included in the SDK 4.0 is the SDK 3.2, which allows applications to be written for the iPad You can get the SDK at http://developer.apple.com/iphone/.
The SDK is free, but you have to register as a developer with Apple to download it Developer membership
is free if you just want to write applications that will run on the included iPhone/iPad simulator If you ally want to install your applications on your device or would like to sell your applications on the Apple iTunes Store, you have to pay a membership fee Currently, the most inexpensive fee is $99 per year.
actu-Installing the iPhone SDK 4.0 requires a Macintosh computer running Mac OS X 10.6.2 (Snow Leopard)
or later.
conventions
To help you get the most from the text and keep track of what’s happening, we’ve used a number of tions throughout the book.
conven-Boxes like this one hold important, not-to-be forgotten information that is
directly relevant to the surrounding text.
Notes, tips, hints, tricks, and asides to the current discussion are offset and
placed in italics like this.
As for styles in the text:
New terms and important words are introduced with
➤
➤ italics where they are defi ned.
Keyboard strokes look like this: Ctrl+A
As you work through the examples in this book, you may choose either to type in all the code manually or
to use the source code fi les that accompany the book All of the source code used in this book is available for download at www.wrox.com Once at the site, simply locate the book’s title (either by using the Search box
or by using one of the title lists) and click the Download Code link on the book’s detail page to obtain all the source code for the book
Trang 27Because many books have similar titles, you may fi nd it easiest to search by ISBN; this book’s ISBN is 978-0-470-87819-4.
Once you download the code, just decompress it with your favorite compression tool Alternately, you can
go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books.
To fi nd the errata page for this book, go to www.wrox.com and locate the title using the Search box or one
of the title lists Then, on the Book Search Results page, click the Errata link On this page you can view all errata that have been submitted for this book and posted by Wrox editors.
A complete book list, including links to errata, is also available at www.wrox.com/
misc-pages/booklist.shtml.
If you don’t spot “your” error on the Errata page, click the Errata Form link and complete the form to send
us the error you have found We’ll check the information and, if appropriate, post a message to the book’s errata page and fi x the problem in subsequent editions of the book.
P2P WroX com
For author and peer discussion, join the P2P forums at p2p.wrox.com The forums are a Web-based system for you to post messages relating to Wrox books and related technologies and interact with other readers and technology users The forums offer a subscription feature to e-mail you topics of interest of your choos- ing when new posts are made to the forums Wrox authors, editors, other industry experts, and your fellow readers are present on these forums.
At http://p2p.wrox.com you will fi nd a number of different forums that will help you not only as you read this book, but also as you develop your own applications To join the forums, just follow these steps:
1 Go to p2p.wrox.com and click the Register link
2 Read the terms of use and click Agree
3 Complete the required information to join as well as any optional information you wish to provide and click Submit
4 You will receive an e-mail with information describing how to verify your account and complete the joining process
Trang 28You can read messages in the forums without joining P2P but in order to post
your own messages, you must join.
Once you join, you can post new messages and respond to messages other users post You can read messages
at any time on the Web If you would like to have new messages from a particular forum e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing
For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to tions about how the forum software works as well as many common questions specifi c to P2P and Wrox books To read the FAQs, click the FAQ link on any P2P page.
Trang 29What’s in this chaPter?
How navigation works on the iPad’s split view
➤
➤Using a toolbar to rotate an image
➤
➤Implementing a simple bank account transaction tracker using a tab bar
➤
➤Navigation is the process of searching through a hierarchy to arrive at the information you desire With the iPhone and iPad, navigating through your data is achieved through the following compo- nents; each has a specifi c viewing philosophy:
on an iPad because of the limited viewing area This is very important if you are planning to develop
an application that will be available on both devices The iPad should not be just a duplicate tion, in terms of visual presentation
applica-When considering navigation design for your applications, consult Apple’s User Interface Guidelines for the iPad as well as the iPhone See Appendix D for documentation sources for these and other developer guides offered by Apple.
1
Trang 30naviGation stack
The navigation process is stack based These views are stacked in a last in, first out (LIFO) manner, which is managed by a View Controller The initial view is the root View Controller, which has views placed over it Unlike the views that are pushed upon it, the root View Controller can never be removed The process of navi- gation involves responding to user interaction, pushing and popping View Controllers on and off the navigation stack Each current view is responsible for pushing the next view onto the stack.
The object that serves as the content provider for navigation items is the navigation bar Users interact with
buttons on the navigation bar, and through delegate messages sent to the View Controller, the pushing or popping of views is performed
the naviGation Bar
The navigation bar basically holds control objects that provide the process of navigating views in an cation The navigation bar provides users with all the controls necessary to push down or pop the views in the application’s hierarchy Processing of the delegate messages is handled by an associated View Controller through the use of delegate methods.
appli-UinavigationBardelegate Protocol
The View Controller implements the methods of this protocol when it has to either push or pop an item onto
or off of the navigation stack.
The methods to implement are as follows:
configuring navigation Bars
The navigation bar is located at the top of the view and will display the title of the current view In addition
to the title, the navigation bar may contain button controls that provide action within the context of the rent view To achieve this functionality, the following are available:
➤ is positioned on the right
The navigation bar itself has a few properties that can be modified:
Trang 31Pushing and Popping items
To navigate from view to view, either to continue drilling down the hierarchy (pushing), or backing out back
up the hierarchy (popping), the process is handled by the view controllers in your application The process of navigation is simply a navigation controller managing a series of view controllers on the navigation stack
A view controller is responsible for pushing (drilling down the hierarchy) and popping (backing out up the hierarchy) other view controllers on or off the navigation stack The process of navigation is simply a navi- gation controller managing a series of view controllers on the navigation stack, and it works like this:
1 The UINavigationController is created
2 The navigation controller pushes the view controller onto the navigation stack
3 The view controller then presents the next view
4 The view controller then dismisses the previous view
a simPle naviGation Bar
In this application navigation will consist of displaying the numbers from 1 to 20 The grouping is even or odd numbers Notice that with the split view of the iPad, portrait orientation presents the navigation bar
as a popover; in landscape orientation, the navigation bar is in the left pane of the split view, as shown in Figure 1-1.
Trang 32development steps: a simple navigation Bar
To create this application that will be the server, execute the following steps:
1 Start Xcode and create a SplitView-based application and name it NavigationBar-iPad If you need to
see this step, please see Appendix A for the steps to begin a SplitView-based application
2 In the Groups & Files section of Xcode, click the Classes group Choose File ➪ New File and select UIViewController subclass then check the UITableViewController subclass option and name it RootDetailViewController
For this application, Interface Builder will not be used, as all the views will be programmatically created Now it is time to enter your logic.
source Code listings for the a simple navigation Bar application
For this application the NavigationBar_iPadAppDelegate.h and NavigationBar_iPadAppDelegate.mfiles are not modified and are used as generated.
RootViewController h Modifications to the Template
The additions to the RootViewController class will be two NSArrays to hold the even and odd numbers The two arrays will be stored in an NSDictionary with even and odd as the keys (see Listing 1-1).
Trang 33listinG 1-1: The complete rootViewController.h file (Chapter1/navigationBar-iPad/Classes/ rootViewController.h)
#import <UIKit/UIKit.h>
@class DetailViewController;
@interface RootViewController : UITableViewController { DetailViewController *detailViewController;
NSDictionary *groupsDict;
NSArray *evenArray;
NSArray *oddArray;
}
@property (nonatomic, retain) IBOutlet DetailViewController *detailViewController;
@property (nonatomic, retain) NSDictionary *groupsDict;
@property (nonatomic, retain) NSArray *evenArray;
@property (nonatomic, retain) NSArray *oddArray;
- (void)initData;
@end
RootViewController m Modifications to the Template
Now that the header file has been updated to define the additions to the template, it is time to modify the RootViewController.m template.
For each of the view properties that were declared, you must match them with @synthesize (see
Trang 34listinG 1-4: TableView display definition
Trang 35listinG 1-5: TableView cell display
#pragma mark -#pragma mark Table view delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSArray *keys = [[[self groupsDict] allKeys]
sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
NSString *key = [keys objectAtIndex:[indexPath row]];
static NSString *CellIdentifier = @”CellIdentifier”;
// Dequeue or create a cell of the appropriate type
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) { cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryNone;
} // Configure the cell
listinG 1-6: TableView cell selected
#pragma mark -#pragma mark Table view delegate
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSArray *keys = [[[self groupsDict] allKeys]
*/
RootDetailViewController *rootDetailViewController = [[RootDetailViewController alloc]
initWithKey:key values:values viewController:[self detailViewController]];
[[self navigationController]
pushViewController:rootDetailViewController animated:YES];
[rootDetailViewController release];
}
The complete RootViewController.m file is shown in Listing 1-7.
Trang 36listinG 1-7: The complete rootViewController.m file (Chapter1/navigationBar-iPad/Classes/ rootViewController.m)
Trang 37return 1;
}
- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section
return [groupsDict count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSArray *keys = [[[self groupsDict] allKeys]
sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
NSString *key = [keys objectAtIndex:[indexPath row]];
static NSString *CellIdentifier = @”CellIdentifier”;
// Dequeue or create a cell of the appropriate type
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) { cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryNone;
} // Configure the cell
*/
RootDetailViewController *rootDetailViewController = [[RootDetailViewController alloc]
initWithKey:key values:values viewController:[self detailViewController]];
Trang 38RootDetailViewController h Modifications to the Template
The RootDetailViewController class will display the actual even or odd values; and when one of the table view cells is selected, the value of the cell will be displayed on the main detail page The complete RootDetailViewController class is shown in Listing 1-8.
listinG 1-8: The complete rootDetailViewController.h file (Chapter1/navigationBar-iPad/ Classes/rootDetailViewController.h)
@property (nonatomic, retain) DetailViewController *detailViewController;
@property (nonatomic, retain) NSString *key;
@property (nonatomic, retain) NSArray *values;
- initWithKey:(NSString *)aKey values:(NSArray *)aValues
viewController:(id)viewController;
@end
RootDetailViewController m Modifications to the Template
Now that the header file has been updated to define the additions to the template, it is time to modify the RootDetailViewController.m template.
Trang 39For each of the view properties that were declared, you must match them with @synthesize (see
[self setValues:aValues];
[self setDetailViewController:viewController];
return self;
}
#pragma mark -#pragma mark View lifecycle
- (void)viewDidLoad { [super viewDidLoad];
- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation { return YES;
Trang 40listinG 1-11: TableView display definition
listinG 1-12: TableView cell display