Tải bản đầy đủ (.pdf) (318 trang)

mac application development by example

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.49 MB, 318 trang )

www.it-ebooks.info
Mac Application Development by
Example Beginner's Guide
A comprehensive and praccal guide, for absolute beginners,
to developing your own App for Mac OS X
Robert Wiebe
BIRMINGHAM - MUMBAI
www.it-ebooks.info
Mac Application Development by Example Beginner's Guide
Copyright © 2012 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system,
or transmied in any form or by any means, without the prior wrien permission of the
publisher, except in the case of brief quotaons embedded in crical arcles or reviews.
Every eort has been made in the preparaon of this book to ensure the accuracy of the
informaon presented. However, the informaon contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers
and distributors will be held liable for any damages caused or alleged to be caused directly
or indirectly by this book.
Packt Publishing has endeavored to provide trademark informaon about all of the
companies and products menoned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this informaon.
First published: December 2012
Producon Reference: 1141212
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-84969-382-0
www.packtpub.com
Cover Image by J.Blaminsky ()
www.it-ebooks.info


Credits
Author
Robert Wiebe
Reviewers
Luca Bernardi
John Dumais
Dominik Jaworek
Jamie B. McHardy
Acquision Editor
James Keane
Lead Technical Editor
Ankita Shashi
Technical Editor
Sharvari Baet
Project Coordinator
Amey Sawant
Proofreader
Steve Maguire
Indexer
Monica Ajmera Mehta
Producon Coordinator
Nilesh R. Mohite
Cover Work
Nilesh R. Mohite
www.it-ebooks.info
About the Author
Robert Wiebe was born in 1961. He has more than 30 years experience designing,
implemenng, and tesng soware. He wrote his rst App in 1979, as a high school
student, using 6502 assembler code on an Ohio Scienc C2-4P computer with 8k RAM.
More recently, he has focused on developing games and ulies for Mac OS X.

His interests include a vintage computer collecon which includes many pre-IBM PC era
microcomputers; Apple Macintosh computers starng with the SE/30 running Mac OS 7
through to the Macbook Pro running Mac OS X that he uses today.
He has developed many popular Mac OS X Apps including ShredIt X, NetShred X, Music Man,
iVCD, and many more.
He has experience developing soware in a number of industries, including mining, nance,
and communicaons. He has worked for a number of employers including Motorola as a
Senior Systems Architect developing two-way wireless data systems and Infowave Soware
as the Soware Development Manager for their Imaging Division. Aer working for other
people's companies, he founded his own companies, Mireth Technology and Burningthumb
Soware, which are his primary interests today.
He is also the author of Unity iOS Essenal book (ISBN 978-1-849691-82-6).
I would like to thank my son, Abram, who is a beginning Mac OS X
programmer himself, for always asking quesons. I would also like to
thank my wife, Donna, for not only encouraging me but also for making it
possible for me to pursue the things I want to do. And nally, I would like
to thank my daughter, Amanda, who keeps me focused on the things that
really maer in life.
www.it-ebooks.info
About the Reviewers
Luca Bernardi is from Milan, Italy. He is 25 years old, has a degree in Computer Science and
he is currently pursuing a Master's Degree in Soware Development and Design. Luca is a
passion-driven iOS engineer and a mobile enthusiast, has developed applicaons that have
been awarded as Apple's App of the Week and top selling app. When he's not programming
he really enjoys learning new things, reading books, and sports such as basketball,
snowboarding, and running.
I want to thank my family, Malde, Claudio, Veronica and Adread who have
always supported me, giving me everything I need to follow my passions.
To my father, Giorgio, who passed away when I was a child, who gave me
my rst computer, an Apple II, and taught me to always follow my passion.

To my amazing girlfriend, Veronica, who always has a smile for me.
John Dumais has over 25 years of experience developing system and circuit simulaon
soware on a wide variety of plaorms, including Mac OS X. He has been using Objecve-C
since StepStone originally introduced it. Most recently, the reviewer has been developing
system monitoring and control soware for iOS devices.
The other book he has reviewed is:
/>html?id=lJRQPgAACAAJ
www.it-ebooks.info
Dominik Jaworek is an experienced SW professional living in Vancouver Area, Brish
Columbia, with his wife and two kids.
He has been working in mobile SW area for more than 14 years experiencing all aspects
of Soware Engineering, starng from development through business analysis, product
management and R&D management. He has also been involved in accessibility technologies
and soluons, and parcipated and presented in the CSUN 2001 conference.
Dominik loves the outdoors and he tries to take every opportunity for trips and hikes with his
family. Also he has always been fascinated with and interested in cars so it's no surprise that
with his engineering soul he is an avid motorsports fan.
Jamie B. McHardy is originally from the Isle of Man. He has worked in the mobile
telecommunicaons domain for over a decade. He has developed embedded middleware
used in millions of devices globally on technologies ranging from communicaon protocols to
audio playback to digital security. Now based in Vancouver, Canada, he is father to one, has a
passion for General Aviaon and is due to wed his beauful ancé in the summer of '13.
www.it-ebooks.info
www.PacktPub.com
Support les, eBooks, discount offers and more
You might want to visit www.PacktPub.com for support les and downloads related to
your book.
Did you know that Packt oers eBook versions of every book published, with PDF and ePub
les available? You can upgrade to the eBook version at
www.PacktPub.com and as a print

book customer, you are entled to a discount on the eBook copy. Get in touch with us at
for more details.
At
www.PacktPub.com, you can also read a collecon of free technical arcles, sign up
for a range of free newsleers and receive exclusive discounts and oers on Packt books
and eBooks.
TM

Do you need instant soluons to your IT quesons? PacktLib is Packt's online digital book
library. Here, you can access, read and search across Packt's enre library of books.
Why Subscribe?
 Fully searchable across every book published by Packt
 Copy and paste, print and bookmark content
 On demand and accessible via web browser
Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib
today and view nine enrely free books. Simply use your login credenals for immediate access.
www.it-ebooks.info
www.it-ebooks.info
Table of Contents
Preface 1
Chapter 1: Our First Program – SimpleCalc 7
Locang developer tools 8
Time for acon - Installing the Xcode App 8
Working with projects 8
Time for acon - creang the SimpleCalc Xcode project 9
Understanding the Xcode project template 14
Time for acon – examine the items in the project navigator 15
Conguring an Xcode project 17
Time for acon - conguring the SimpleCalc Xcode project 17

Running an App 21
Time for acon – run the SimpleCalc App 21
Customizing an Xcode template's interface 23
Time for acon – creang the SimpleCalc interface 23
Customizing an Xcode template's implementaon 32
Time for acon – implement the SimpleCalc behavior 32
Building an App 34
Time for acon – building and installing the SimpleCalc App 34
Summary 37
Chapter 2: Debugger – Finding and Fixing Problems 39
The Debug area in Xcode 40
Time for acon – displaying the Debug area in Xcode 40
The Debug area appears on its own 41
Time for acon - integer division by zero 42
Examining variable values in the debugger 45
Time for acon – examining a variable value 45
Unexpected App behavior – no debugger? 46
Time for acon – index out of range 46
www.it-ebooks.info
Table of Contents
[ ii ]
Using breakpoints to get more informaon from Xcode 49
Time for acon – set a breakpoint 50
Summary 52
Chapter 3: System Preferences – NewDefaults 53
Understanding preference panes 54
The transion to 64 bit from 32 bit 54
Creang an Xcode preference pane project 55
Time for acon – creang the NewDefaults Xcode project 55
Conguring an Xcode preference pane project 60

Time for acon – customizing the icon and copyright 60
Customizing the preference pane template interface 62
Time for acon – creang the NewDefaults interface 63
Customizing the preference pane Xcode template's .h implementaon 69
Time for acon – compleng the NewDefaults.h interface denion 69
Customizing the preference pane Xcode template's .m implementaon 72
Time for acon – compleng the NewDefaults.m implementaon 72
Implemenng the readDefaults:forKey: method 73
Time for acon – wring the readDefaults:forKey: program code 73
Implemenng the didSelect: method 78
Time for acon – wring the didSelect: program code 78
Implemenng themyBuonAcon: method 81
Time for acon – wring the myBuonAcon: program code 81
Summary 84
Chapter 4: Business Applicaon – Global Currency Converter 85
Designing the GUI for global currency converter 86
Time for acon – creang our project and GUI 86
Connecng the GUI to program elements 88
Time for acon – connecng the App Delegate to the GUI 88
What is an XML le? 90
Format of the XML le we will download 90
Time for acon – downloading an XML le 90
Parsing an XML document 92
Time for acon – parsing the XML Document 93
How to invoke a background thread 98
Time for acon – invoking a background thread 98
Managing a pop-up menu 101
Time for acon – implemenng the program code for the pop-up menu 101
Creang the Table View Interface 102
Time for acon – conguring the table view in Interface Builder 103

Creang the table view implementaon 110
www.it-ebooks.info
Table of Contents
[ iii ]
Time for acon – implemenng the dataSource and delegate 110
Summary 115
Chapter 5: Personal Informaon – Numbers in the iCloud 117
What is iCloud? 117
Installing an iCloud enabled development prole 118
Time for acon – creang and installing an iCloud enabled development prole 119
Designing the GUI for numbers in the cloud 120
Time for acon – creang our project and GUI 121
Connecng the GUI to program elements 124
Time for acon – connecng the App Delegate to the GUI 125
Using two tables in one window 129
Time for acon – implemenng the TableView delegate 130
Implemenng the toolbar 137
Time for acon – implemenng the Toolbar delegate 137
Accessing iCloud 144
Time for acon – accessing iCloud for key-value storage 144
Summary 152
Chapter 6: Painng – Mul-nger Paint 153
What is mul-touch? 154
Implemenng a custom view 154
Time for acon – creang a GUI with a custom view 155
How to receive mul-touch events 159
Time for acon – drawing our ngers 160
How to manage the mouse cursor 166
Time for acon – detaching the mouse cursor from the mouse hardware 166
Performing 2D drawing in a custom view 171

Time for acon – drawing the acve strokes 172
Saving strokes 180
Time for acon – saving the strokes 180
How to receive gesture events 187
Time for acon – handling rotate gestures 188
Summary 190
Chapter 7: Capturing Sll Images – iSight iMage cApture App 191
What is Image Kit? 192
Adding framework to a project 192
Time for acon – creang a project and adding the Quartz framework 192
Browsing images 193
Time for acon – implemenng the interface for browsing our pictures folder 194
Time for acon – implemenng the methods for browsing our Pictures folder 200
Capturing and saving images 210
www.it-ebooks.info
Table of Contents
[ iv ]
Time for acon – capturing and saving images 211
Modifying the behavior of the Picture Taker 214
Time for acon – drawing our ngers 215
Deleng images 217
Time for acon – deleng an image 217
Summary 218
Chapter 8: Video Recording – iSight Recorder 219
What is Quickme Kit Capture? 220
Previewing the video capture 220
Time for acon – creang a project and adding the program code to
preview video and audio 221
Capturing a single frame as a sll image 225
Time for acon – capturing a frame 226

Previewing audio capture 232
Time for acon – capturing and saving images 232
Capturing a movie to disk 235
Time for acon – capturing a Quickme movie 235
Capturing compressed movies to disk 241
Time for acon – saving a compressed movie 241
Summary 250
Chapter 9: Video Recording – Full Screen iSight Recorder 251
What is the full screen mode? 252
Enabling the full screen mode 252
Time for acon – enabling full screen mode in iSight Recorder 252
Disabling auto layout 254
Time for acon – using the tradional layout model 254
Modifying our user interface to take advantage of full screen 259
Time for acon – rening how we enter and exit full screen 259
Time for acon – rening text colors 265
Time for acon – rening controls using fading 267
Customizing the full screen window size 272
Time for acon – adding a full screen window that has depth 272
Customizing the full screen animaon 274
Time for acon – customizing the full screen animaon 274
Summary 280
Chapter 10: Sharing Our App with Others – Becoming a Mac Developer 281
What is the Mac developer program? 282
What are the benets of joining the Mac developer program? 282
Access to Development Videos, including World Wide Developer
Conferences sessions 283
www.it-ebooks.info
Table of Contents
[ v ]

Access to the Mac OS X Developer Library 283
Access to the Apple bug reporter system 283
Access to pre-release (beta) soware 283
The opportunity to join a paid developer program 283
Access to developer forums 284
Code level technical support 284
Access to iCloud services 284
A developer ID for gatekeeper 284
The ability to distribute our App through the Mac App store 284
Step by step developer program sign up 284
Time for acon – joining the Mac developer program 285
More developer tools 286
Time for acon – accessing the online developer tools 287
What is code signing? 287
What is Gatekeeper? 288
Signing an App with a Developer ID 289
Time for acon – signing an App with our Developer ID 289
Summary 292
Index 293
www.it-ebooks.info
www.it-ebooks.info
Preface
Apple is taking the world by storm. Their market share is growing faster than the industry
average and has been for years. So, it's never been more important to have the ability
to develop an App for Mac OS X. Whether it's a System Preference, a business app that
accesses informaon in the Cloud, or an applicaon that uses a mul-touch trackpad or uses
a camera, you will need a solid foundaon in app development to get the job done.
Mac Applicaon Development by Example takes you through all the aspects of using the
Xcode development tool to produce complete working apps that cover a broad range of
topics. This comprehensive book on developing applicaons covers everything a beginner

needs to know and demonstrates the concepts using examples that take advantage of some
of the most interesng hardware and soware features available.
You will discover the fundamental aspects of OS X development while invesgang
innovave plaorm features to create a nal product that takes advantage of some of the
unique aspects of OS X.
You will learn how to use Xcode tools to create and share Mac OS X Apps and explore
numerous OS X features including iCloud, mul-touch trackpad, and the iSight camera.
Using fundamental development concepts and innovave plaorm features, this book
provides you with an illustrated and annotated guide to bring your ideas to life!
What this book covers
Chapter 1, Our First Program – SimpleCalc, covers how to get up and running with the
Xcode Integrated Development Environment (IDE). We create an App icon, a user interface,
implement the App behavior, and build and run the App with Xcode.
www.it-ebooks.info
Preface
[ 2 ]
Chapter 2, Debugger – Finding and Fixing Problems, covers the concept of debugging our
program code. We learn how to explore our program code when the debugger is invoked,
how to change the values of our variables with the debugger, and how to use the debugger
to nd and x problems in our program.
Chapter 3, System Preferences – NewDefaults, covers creang our own System Preference
plugin and learning how to run command-line tools from within the System Preference to
customize the behavior of the Mac OS X Finder.
Chapter 4, Business Applicaon – Global Currency Converter, covers how to get
publicly-available data from the Internet and use it to create a currency converter. We will
download an XML le from the Internet and extract the informaon that we need from it
into our program. We learn how to access the Internet using a background thread so that
our user interface does not freeze while we wait for the XML le to download. Finally, we
learn how to use pop-up menus, table views, and how to perform arithmec operaons on
an array of numbers.

Chapter 5, Personal Informaon – Numbers in the iCloud, how to take your data and store
it on the Internet using Cloud services Cloud services. Cloud services are popping up
everywhere. We learn about Apple's iCloud and how to store and retrieve informaon from
the iCloud servers. Along the way, we learn how to implement two table views in the same
window and how to implement a toolbar.
Chapter 6, Painng – Mul-nger Paint, covers mul-touch. Mobile compung has
introduced a new way of interacng with computer touches and gestures. Laptop and
desktop compung have adopted this trend through the use of mul-touch trackpads.
In this chapter, we learn about mul-touch, including how to handle mul-touch and
gesture events. We also learn how to use the 2D drawing features of Mac OS X to draw
into custom views.
Chapter 7, Capturing Sll Images – iSight iMage cApture App, covers how to use the Image
Kit Framework to capture and manipulate sll images using the iSight camera.
Chapter 8, Video Recording – iSight Recorder, covers capturing videos. While capturing sll
images is nice, capturing movies is beer. In this chapter, we learn how to use Quickme Kit
Capture to preview Video and Audio, to capture sll frames, and to record movies using the
iSight camera.
Chapter 9, Video Recording – Full Screen iSight Recorder, covers how to convert a windowed
App to a full screen App. We'll learn how to convert our iSight Recorder App to a full screen
App, including enhancing the user interface, giving the screen an illusion of depth, and
implemenng the animaons used to enter and exit full screen.
www.it-ebooks.info
Preface
[ 3 ]
Chapter 10, Sharing our App with others – Becoming a Mac developer. Now that we know
how to create Mac OS X Apps, we'll want to share them. This chapter explores both the free
and paid Apple developer programs - describing the features of each as well as explaining
how to join them and why you might want to. It also explains code signing - what it is and
how to do it. Then we'll be able to share our Mac Apps and have them interact nicely with
modern security soware like Gatekeeper on Mac OS X 10.8.

What you need for this book
You need a Mac OS X computer capable of running Mac OS X 10.7 or later. Some App
features require Mac OS X 10.8. You also need to install Xcode Version 4 from the Mac
OS X App store. Xcode is a free download.
Who this book is for
This book is for people who are programming beginners and have a great idea for a Mac OS X
app and need to get started.
Conventions
In this book, you will nd a number of styles of text that disnguish between dierent
kinds of informaon. Here are some examples of these styles, and an explanaon of
their meaning.
Code words in text are shown as follows: "In the le named
BTSAppDelegate.h use the
#import direcve to import the <QTKit/QTKit.h> le so that the QTKit interface objects
can be referenced."
A block of code is set as follows:
// Define two local variables
// that will contain the results
// of various operations
BOOL l_success = NO;
NSError* l_error;
When we wish to draw your aenon to a parcular part of a code block, the relevant lines
or items are set in bold:
// Define two local variables
// that will contain the results
// of various operations
BOOL l_success = NO;
NSError* l_error;
www.it-ebooks.info
Preface

[ 4 ]
New terms and important words are shown in bold. Words that you see on the screen, in
menus or dialog boxes for example, appear in the text like this: "When we click the Next
buon, Xcode will ask us to select opons for our new project".
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this
book—what you liked or may have disliked. Reader feedback is important for us to develop
tles that you really get the most out of.
To send us general feedback, simply send an e-mail to
, and
menon the book tle through the subject of your message.
If there is a topic that you have experse in and you are interested in either wring or
contribung to a book, see our author guide on
www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you
to get the most from your purchase.
Downloading the example code
You can download the example code les for all Packt books you have purchased from
your account at . If you purchased this book elsewhere,
you can visit and register to have the les
e-mailed directly to you.
www.it-ebooks.info
Preface
[ 5 ]
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do
happen. If you nd a mistake in one of our books—maybe a mistake in the text or the

code—we would be grateful if you would report this to us. By doing so, you can save other
readers from frustraon and help us improve subsequent versions of this book. If you
nd any errata, please report them by vising
selecng your book, clicking on the errata submission form link, and entering the details of
your errata. Once your errata are veried, your submission will be accepted and the errata
will be uploaded to our website, or added to any list of exisng errata, under the Errata
secon of that tle.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt,
we take the protecon of our copyright and licenses very seriously. If you come across any
illegal copies of our works, in any form, on the Internet, please provide us with the locaon
address or website name immediately so that we can pursue a remedy.
Please contact us at
with a link to the suspected pirated material.
We appreciate your help in protecng our authors, and our ability to bring you
valuable content.
Questions
You can contact us at if you are having a problem with any
aspect of the book, and we will do our best to address it.
www.it-ebooks.info
www.it-ebooks.info
1
Our First Program – SimpleCalc
This chapter will walk us through the steps needed to set up Xcode as well as
the development of the SimpleCalc App. SimpleCalc will allow us to take two
numbers and perform addition, subtraction, multiplication, and division. This
App is intentionally kept simple because we have many things to learn about
how to develop Apps in this chapter.
In this chapter, we shall learn the following:
 Installing the Xcode App

 Creang a new Xcode project
 Conguring an Xcode project
 Creang an App Icon
 Conguring an Xcode target
 Creang a user interface
 Implemenng a Mac OS X App behavior
 Building and running a Mac OS X program
www.it-ebooks.info
Our First Program – SimpleCalc
[ 8 ]
Locating developer tools
Before we start to develop our rst Mac OS X program, we need to locate the tools needed
to create programs. There are several dierent choices for soware development on Mac OS
X and the tools that we will select depend on the programming environment that we want
to use. Because we want to write our programs using the nave Objecve-C programming
language and the Cocoa frameworks we are going to use Apple's free Integrated
Development Environment (IDE), called Xcode.
The code in this book has been developed and tested with Xcode 4.3.
Cocoa frameworks
The Cocoa frameworks consist of libraries, Applicaon Programming
Interfaces (APIs), and runmes that form the development layer for all
of Mac OS X. By developing with Cocoa, we will be creang applicaons
the same way Mac OS X itself is created. Our applicaon will
automacally inherit the behavior and appearances of Mac OS X. Using
Cocoa with Xcode IDE is the best way to create nave Mac applicaons.
Time for action - Installing the Xcode App
For Mac OS X, Apple provides the Xcode IDE for free in the Mac OS X App store. We are going
to install the Xcode IDE so that we can start making our rst App. To do this, we need to
follow these steps:
1. Access the Mac App store by clicking on the Apple menu and selecng App Store.

2. Search the App Store to locate the Xcode App.
3. Install the Xcode App from the App store.
What just happened?
Because Apple distributes Xcode through the Mac App store, we were able to nd and install
developer tools in the same way we would nd any App that is available in the store.
Working with projects
When we want to build a Mac OS X App, we need to rst create an Xcode project. The Xcode
project is the place that we keep all of the parts (code, icons, user interface, and images) that
Xcode will put together to build our App.
www.it-ebooks.info
Chapter 1
[ 9 ]
Time for action - creating the SimpleCalc Xcode project
Now that we have installed Xcode, we can start using it to write our own Mac OS X App.
Let's get started:
1. To create a new Xcode project, launch the Xcode App and click the buon tled
Create a new Xcode project on the Welcome to Xcode window as shown in the
following screenshot:
www.it-ebooks.info
Our First Program – SimpleCalc
[ 10 ]
2. When Xcode asks us to select a template, select Applicaon under Mac OS X and
Cocoa Applicaon as the template. Then, click on the Next buon.
3. When we click the Next buon, Xcode will ask us to select opons for our new
project. The opons that we need to select are as follows:
Option Value Description
Product Name
SimpleCalc The product name will be the name
of your App program file that shows
up in the Mac OS X Finder.

Company Identifier
com.yourdomain The company identifier needs to
be unique and typically uses the
reverse domain notation. It can
be anything but you should use a
company identifier that will not
conflict with an existing company.
If you don't have an Internet
domain name you can acquire
one new or you can use
com.yourlastname.first name.
Class Prefix
Your Initials
(For consistency,
throughout this
book we will use
BTS but when you
develop your own
code you should
use your own
initials)
The class prefix is used to make
sure any program classes that you
create do not have the same name
as any program classes that some-
one else may create.
www.it-ebooks.info

×