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

Learn Cocoa on the Mac potx

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 (20.56 MB, 393 trang )

Nutting
Cocoa on the Mac
Learn
Companion
eBook
Available
Trim: 7.5 x 9.25 spine = 0.875" 392 page count
Mastering Mac OS X’s Cocoa Frameworks,
with Xcode and Objective-C
Jack Nutting
|
David Mark
|
Jeff LaMarche
Learn
Cocoa
on the Mac
COMPANION eBOOK SEE LAST PAGE FOR DETAILS ON $10 eBOOK VERSION
US $39.99
Shelve in
Mac
User level:
Beginner-Intermediate
www.apress.com
SOURCE CODE ONLINE
BOOKS FOR PROFESSIONALS BY PROFESSIONALS
®
ISBN 978-1-4302-1859-3
9 781430 218593
5 39 9 9
this print for content only—size & color not accurate


CYAN
MAGENTA
YELLOW
BLACK
PANTONE 123 C
SPOT MATTE
L
earn Cocoa on the Mac presents complete coverage of the latest Cocoa
frameworks in a logical, step-by-step progression of discussions and tutori-
als. The base frameworks are introduced and demonstrated: AppKit for all the
standard graphical controls and the Foundation framework classes for Objec-
tive-C. You’ll dig into the basic UI objects and then attack the fundamentals of
Cocoa Bindings, part of Apple’s comprehensive implementation of the Model-
View-Controller (MVC) design pattern.
Then it’s on to a comprehensive look at Core Data, the key to all data-driv-
en applications, from basic concepts to data modeling and even more ad-
vanced data techniques. You’ll also learn drawing with Core Graphics and
Core Animation, le management, as well as the latest technique introduced
with Snow Leopard: using Grand Central Dispatch to make your applications
concurrent, in order to make the most of today’s multi-core processors.
Through a combination of pragmatic problem-solving and a deep respect
for Cocoa’s underlying design philosophies, you’ll learn about the diverse
capabilities of the various APIs and then how to put them all to use in dy-
namic combinations. And when you’re done, you’ll have an integrated view
of Cocoa’s components and how to use them to build great Mac OS X apps
with this rich and mature toolset.
What you’ll learn

How to build your own Cocoa applications—this is much more than
just a quick introduction to Cocoa!


What makes Cocoa and its MVC architecture tick

Ecient coding techniques for stitching together powerful APIs

How to leverage Cocoa’s design patterns and put them to proper use
in your own code
Who is this book for?
Those new to Mac OS X development with a basic understanding of object-
oriented programming and seasoned developers who want to master the lat-
est Cocoa frameworks, as well as iPhone developers who want to extend their
knowledge of Cocoa Touch to include Mac-specic technologies.
Jack Nutting, veteran Cocoa expert back to the early days of NextStep,
along with Dave Mark and Je LaMarche, the bestselling authors of
Beginning iPhone 3 Development, share their knowledge of and keen
insights for making great Mac OS X apps.
RELATED TITLES
www.it-ebooks.info

www.it-ebooks.info
i
Learn Cocoa on the Mac





■ ■ ■
Jack Nutting,
Dave Mark and

Jeff LaMarche


www.it-ebooks.info
ii
Learn Cocoa on the Mac
Copyright © 2010 by Jack Nutting, David Mark and Jeff LaMarche
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any
means, electronic or mechanical, including photocopying, recording, or by any information
storage or retrieval system, without the prior written permission of the copyright owner and the
publisher.
ISBN-13 (pbk): 978-1-4302-1859-3
ISBN-13 (electronic): 978-1-4302-1860-9
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names may appear in this book. Rather than use a trademark symbol with every
occurrence of a trademarked name, we use the names only in an editorial fashion and to the
benefit of the trademark owner, with no intention of infringement of the trademark.
President and Publisher: Paul Manning
Lead Editors: Clay Andres, Brian MacDonald, Matthew Moodie, Douglas Pundick
Technical Reviewer: Mark Dalrymple
Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell,
Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan
Parkes, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic
Shakeshaft, Matt Wade, Tom Welsh
Coordinating Editor: Mary Tobin
Copy Editor: Tracy Brown Collins
Compositor: MacPS, LLC
Indexer: John Collin
Artist: April Milne
Cover Designer: Anna Ishchenko

Photo Credit: Weronica Meijer
Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th
Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-
, or visit .
For information on translations, please e-mail , or visit .
Apress and friends of ED books may be purchased in bulk for academic, corporate, or
promotional use. eBook versions and licenses are also available for most titles. For more
information, reference our Special Bulk Sales–eBook Licensing web page at

The information in this book is distributed on an “as is” basis, without warranty. Although every
precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall
have any liability to any person or entity with respect to any loss or damage caused or alleged to
be caused directly or indirectly by the information contained in this work.

www.it-ebooks.info
iii



www.it-ebooks.info
iv

Contents at a Glance
■Contents at a Glance iv
■Contents v
■Foreword xi
■About the Authors xii
■About the Technical Reviewer xiii
■Acknowledgments xiv
■Preface xv

■Chapter 1: Must Love Cocoa 1
■Chapter 2: Hello, World 5
■Chapter 3: Lights, Camera… Actions! (and Outlets, Too) 29
■Chapter 4: GUI Components 55
■Chapter 5: Using Table Views 91
■Chapter 6: Cocoa Bindings 105
■Chapter 7: Core Data Basics 133
■Chapter 8: Core Data Relationships 165
■Chapter 9: Search and Retrieve Core Data with Criteria 183
■Chapter 10: Windows and Menus and Sheets 197
■Chapter 11: Document-Based Applications 221
■Chapter 12: Exceptions, Signals, Errors, and Debugging 239
■Chapter 13: Drawing in Cocoa 259
■Chapter 14: Advanced Drawing Topics 279
■Chapter 15: Working with Files 303
■Chapter 16: Concurrency 315
■Chapter 17: Future Paths 335
■Index 347

www.it-ebooks.info
v


Contents
■Contents at a Glance iv
■Contents v
■Foreword xi
■About the Authors xii
■About the Technical Reviewer xiii
■Acknowledgments xiv

■Preface xv

■Chapter 1: Must Love Cocoa 1
Get a Mac and Download the Tools 2
Download the Source Code 3
Getting Help 3
What You Need to Know Before You Begin 3
Are You Ready? 4
■Chapter 2: Hello, World 5
Building “Hello, World” 5
Exploring the Nib File 9

The Library 10
Dragging Out a Label 12
Using the Blue Guidelines 13
The Inspector Window 14
The Attributes Inspector 15
Change the Label’s Color and Font 17
Using the Menu Editor 19
Creating Your Application Icon 21
Adding Your Icon to Your Project 22
Property Lists 25
Running Your Application 25

www.it-ebooks.info
■ CONTENTS
vi
Sharing Your Creation With the World 26
Goodbye, Hello World 28


■Chapter 3: Lights, Camera… Actions! (and Outlets, Too) 29
This Chapter’s Application 30
Frameworks, Frameworks Everywhere 30
The Foundation Framework 31
The AppKit Framework 31
The Cocoa Way: Model-View-Controller 32
Outlets, Actions, and Controllers 33
Declaring Outlets 33
Declaring Actions 34
Outlets and Actions in Action 35
Enabling Garbage Collection 35
Creating Our Controller Class 37
Declaring an Action and Outlet 38
Back to Interface Builder 39
Setting Up the Window 42
Designing the Window’s Interface 46
Connecting the Outlet 48
Connecting the Buttons to Our Action 49
Implementing the Action Method 50
The Application Delegate 51
Configuring the Application to Quit on Window Close 52
Using the Documentation Browser 53
Bring It on Home 54
■Chapter 4: GUI Components 55
Creating the VillainTracker Application 57
Creating the VillainTrackerAppDelegate Class 58
Planning for the GUI 60
Building Your Interface 62
Bringing Out Your Text Fields 62
Letting them Pick Dates 64

Creating the Combo Box 65
Indicating a Rating with a Level Indicator 66
Adding Radio Buttons in a Matrix 67
Adding an Image View 70
Adding Checkboxes in a Matrix 71
Configuring a Popup Button 72
Inserting a Text View 73
Making Logical Groupings 73
Resizing 76
Time for the Controller 78
Making All the Connections 78
Getting Started with Coding 80
Standardizing Key Names 80
Creating the Default Villain 81
Paying Attention to Detail 82

www.it-ebooks.info
■ CONTENTS
vii
Responding to Input 87
In Conclusion 90
■Chapter 5: Using Table Views 91
Preparing AppController for Multiple Villains 91
Making Way for the Table View 93
Tweaking the Autosizing Characteristics 96
Making Some New Connections 98
Making Way for the Table View: Code Edition 99
The Table View Needs Your Help 100
Adding and Deleting Villains 102
In Conclusion 104

■Chapter 6: Cocoa Bindings 105
Binding to Simple Controls 106
Create the DungeonThing Project 106
Create a Preferences Window 107
Binding to NSUserDefaultsController 111
Create the Main Window 114
Set Up the DungeonThingAppDelegate 116
Define Your Constants 116
Specify Default Preferences Values 117
Create the Action Methods 118
Binding to a Table View 120
Make the Code Bindings-Ready 121
Show History in Tables 124
Create and Configure an Array Controller 126
Bind Table Display via the Array Controller 128
Bind a Text Field via the Array Controller’s Selection 128
Making Sure it Works 129
Rinse, Repeat, Rinse, Repeat 129
Okay, But How Did That Work? 129
Key-Value Coding 129
Key-Value Observing 131
Cocoa Bindings: How It Works 131
In Conclusion 132
■Chapter 7: Core Data Basics 133
What You’ve Been Missing 133
Creating MythBase 135
Defining the Model 136
The Automatic GUI 142
Refining the GUI 145
Exploring the Template Code 150

The App Delegate Interface 150
The App Delegate Implementation 152
Adding Business Logic 159
Validating Single Attributes 160
Validating Multiple Attributes 160
Creating a Custom Attribute 163

www.it-ebooks.info
■ CONTENTS
viii
In Conclusion 164
■Chapter 8: Core Data Relationships 165
Modeling New Entities and Relationships 166
Model Versioning and Migrations 167
Preparing for Multiple Model Versions 167
Adding New Entities 167
Add Relationships 168
Creating a Simple Migration 170
Time to Run 172
Updating the GUI 173
Create the Band Window 173
Giving Useful Names to Array Controllers 174
Putting People in Bands 175
Showing the Bands’ Members 177
Create a Venue Window 179
Adding a Gig List to the Band Window 179
Wrapping Up Relationships 181
■Chapter 9: Search and Retrieve Core Data with Criteria 183
Creating QuoteMonger 183
Create the Project and Its Data Model 184

The Data Entry Window 185
Creating the Quote Finder Window 188
Limiting Results with NSPredicate 189
Creating Predicates 189
Specifying an NSAppController’s Predicate in Interface Builder 191
User-Defined Predicates 191
Adding a Predicate to the App Delegate 192
Add a Predicate Editor to the Search Window 193
Configuring the Predicate Editor 193
Saving a Predicate 195
In Conclusion 196
■Chapter 10: Windows and Menus and Sheets 197
NSWindow and NSPanel 197
Standard System Panels 201
A Controller With a Nib of Its Own 205
Modal Windows 209
System Menus 211
Standard Application Menu Items 212
Your Own Menus 212
Sheets 218
Wrap-up 220
■Chapter 11: Document-Based Applications 221
Creating the ColorMix Application 222
Examining the Default Nib Files 223
Defining the Model 223
Setting Two Colors 224
The Simplest of GUIs 225

www.it-ebooks.info
■ CONTENTS

ix
Creating a Default ColorSet 226
Settling on a File Format 227
Adding Color 227
The ColorBlendView Class 228
Adding Blended Colors to the GUI 230
Adding Some Background Bling 234
About Undo and Redo 236
The Undo Stack 236
In Conclusion 237
■Chapter 12: Exceptions, Signals, Errors, and Debugging 239
Exception Handling 239
Catching Exceptions 240
The Limited Role of Exceptions in Cocoa 241
Create a Test-bed 241
NSInvalidArgumentException 246
NSRangeException 249
And the Rest 250
Worse than Exceptions: Death by Signal 251
NSError 253
Domains and Codes 253
Realizing You Have an Error 254
Presenting an Error 258
In Conclusion 258
■Chapter 13: Drawing in Cocoa 259
Fundamentals 259
The View Coordinate System 260
Frame Rectangle vs. Bounds Rectangle 260
Rects, Points, and Sizes 261
Path Basics 261

Creating an NSView Subclass 262
Some C Structures 262
The Basic Drawing Method, drawRect: 263
Graphics States 263
Path Helpers 263
Colors and the Graphics Context 264
Beyond Color 265
Manual Path Construction 266
Pushing Boundaries 266
LOLmaker 269
First Steps to LOL 269
LOLView 271
Printing Basics 277
Wrapping Up 278
■Chapter 14: Advanced Drawing Topics 279
Editing a Curve 279
Preparations 280
Bezier Plumbing 282

www.it-ebooks.info
■ CONTENTS
x
Drawing a Curve 283
Watching the Mouse 285
A Little Polish 287
Core Animation: A Primer 288
Core Animation Basics 289
Implicit Animations 289
Explicit Animations 290
Grouping Animations 295

What Have We Done? 302
■Chapter 15: Working with Files 303
Implicit File Access 303
High-level File Operations 304
What About That File: The Code 305
What About That File: The GUI 310
Filing It All Away 314
■Chapter 16: Concurrency 315
SlowWorker 316
Threading Basics 318
Units of Work 319
Operation Queues 320
Vitalizing SlowWorker 320
Extending NSObject 323
Demanding the Main Thread 324
GCD: Low-Level Queuing 329
Becoming a Blockhead 330
Improving SlowWorker a Second Time 331
Another Option: NSBlockOperation 333
A Little Concurrency Goes a Long Way 334
■Chapter 17: Future Paths 335
More Cocoa-isms 335
Notifications 336
Blocks 337
Cocoa in a Foreign Language 339
PyObjC 340
MacRuby 341
Nu 342
JavaScript 342
F-Script 343

Ported Cocoa 343
Cocoa Touch 344
GNUstep and Cocotron 344
Cappuccino/Objective-J 345
Here at the End of All Things 346
■Index 347

www.it-ebooks.info

xi

Foreword
Beware Dave Mark bearing new ideas.
You’ve probably seen Dave’s name on the cover of the Apress Mac and iPhone books.
Actually, his name is on the cover of this book. He’s the Mac and iPhone series editor, he knows
how to get stuff done, and I wish I had half of Dave’s energy. And, if you’re a friend of Dave’s, he’ll
put you to work. He’s put me to work over the years (in addition to my day job).
“Hey, MarkD, I have this idea for an introductory Objective-C book. Why don’t you and
Scott Knaster write it?” Sounds like fun, and it was. I still chuckle at some of jokes that we targeted
to very narrow slices of nerdom.
“Hey, MarkD, Jeff LaMarche and I have this idea for an iPhone SDK book, want to be
technical reviewer for it?” Sounds like fun, and it was. Then they did another iPhone book, which
I got to review. I discovered that this technical reviewing thing is pretty awesome.
Just think of it. You get to read a nerdy book before it comes out. You get to learn cool new
stuff along the way. Best of all, you get to poke holes in the text and code, kibitz and generally
make random suggestions. And then you don’t actually have to do the work involved in fixing it!
And you get paid for it! My spousal overunit lets me keep any money I make off of books, so it’s
mine to play with. Daddy’s camera needs a new lens.
Anyway, Dave calls up and says, “Hey MarkD, I have this idea for a Cocoa book, want to be
the technical reviewer for it?” Sounds like fun. Daddy needs a new 85mm f/1.8.

So I “meet” this Jack Nutting guy via email. I GoogleStalk for anything interesting. We chat a bit. I
start getting chapters to review. They’re interesting. They’re informative. I’m learning stuff. (oh, so
that’s how NSPopupMenu bindings work). And they’ve got a fun streak. I very rarely LOL in real life when
I’m at the computer, but there was a time or two where I was totally C|N>K. Then I had to explain
“C|N>K” to everyone in the publishing pipeline because I wrote it in the reviewer comments.
I had my doubts. Cocoa is a huge topic. The typical Mac OS X desktop application takes a lot
more work, and uses a lot more technology and Cocoa classes than the typical iPhone
application. Some parts of Cocoa are kind of old and crufty, it being a 20-year-old toolkit. Some
parts of Cocoa are totally the new shiny. But no matter what kind of Cocoa app you’re writing,
you have to know something about a lot of stuff before you can really get started.
Jack’s picked the current best-of-breed techniques for making applications in Mac OS X
10.5 and 10.6 (and beyond). There’s enough breadth to know what you need to know, enough
depth to get you up and running, and enough knowledge to dig deeper on your own.
I hope you enjoy reading this book. I truly enjoyed reviewing it.

Cheers,
++md

P.S. C|N>K means “coffee piped through nose into keyboard”

Mark Dalrymple

www.it-ebooks.info

xii

About the Authors
Jack Nutting has been using Cocoa since the olden days, long before it was
even called Cocoa. He’s used Cocoa and its predecessors to develop software
for a wide range of industries and applications including gaming, graphic

design, online digital distribution, telecommunications, finance, publishing,
and travel. When he’s not working on Mac or iPhone projects, or developing
web applications with Ruby on Rails, he’s usually spending time with his
family. Jack is a passionate proponent of Objective-C and the Cocoa
frameworks. At the drop of a hat, he will speak at length on the virtues of
dynamic dispatch and runtime class manipulations to anyone who’ll listen
(and even to some who won’t). He blogs from time to time at
.

Jeff LaMarche is a long-time Mac developer, and Apple iPhone Developer.
With over 20 years of programming experience, he’s written on Cocoa and
Objective-C for MacTech Magazine, as well as articles for Apple’s Developer
Technical Services website. He has experience working in Enterprise
software, both as a developer for PeopleSoft starting in the late 1990s, and
then later as an independent consultant.






Dave Mark is a long-time Mac developer and author and has written a
number of books on Macintosh development, including Learn C on the
Macintosh, The Macintosh Programming Primer series, and Ultimate Mac
Programming. His blog can be found at .


www.it-ebooks.info

xiii


About the Technical
Reviewer
Mark Dalrymple is a long-time Mac and Unix programmer, working on cross-
platform toolkits, Internet publishing tools, high-performance web servers,
and end-user desktop applications. He is also the principal author of
Advanced Mac OS X Programming (Big Nerd Ranch, 2005) and Learn
Objective-C on the Mac (Apress, 2009). In his spare time, Mark plays trombone
and bassoon, and makes balloon animals.

www.it-ebooks.info

xiv

Acknowledgments
This book would never have been possible without contributions from many people. Clay Andres’
expert guidance and helpful insights into the publishing process have helped keep me on track
numerous times. Dave Mark’s feedback and concrete writing tips have been absolutely essential;
believe me, you don’t want to see the first draft of the first chapter I wrote, before Dave started
setting me straight. Jeff LaMarche’s work on the first chapters of the book, as well as his initial
outline for the rest of the book, provided a solid foundation for me to build upon. Mark
Dalrymple has done a great job of examining the book’s technical details with a fine-toothed
comb, keeping me honest and making me look good at the same time. Brian MacDonald’s
vantage point as someone with great technical knowledge, but not detailed experience with
Cocoa, helped uncover bits and pieces of the book that needed to be expanded or compacted.
Throughout the last several months of the writing, Mary Tobin has been consistently patient and
helpful with this newbie author, keeping track of the statuses of each chapter and keeping the
process working smoothly. And copy-editor Tracy Brown Collins has responded to a deluge of
way-past-deadline chapters with remarkable efficiency and a keen eye for detail. Beyond that,
there are any number of people involved in the layout and other aspects of the production who

are, to me, completely unknown and nameless, despite their crucial contributions. Thank you,
whoever you are!
Apart from the people associated with Apress, a number of friends have helped in a variety of
ways, at various stages during the creation of this book, either volunteering their time freely or at
least answering my pleas for advice. Saurabh Sharan has given great feedback on nearly every
chapter of the book, helping locate sections that needed further clarification. Joar Wingfors
provided detailed commentary on several chapters, as well as a handy bit of public domain code
that we used in Chapter 11. Tim Burks provided some important feedback on the final chapter. I
owe a huge debt of gratitude to Tom Geller, who put me in touch with Apress in the first place;
without Tom putting two and two together, I’d still be sitting here wondering if I’d ever write
anything “real”. Finally, I’d like to thank my wife Weronica Meijer and our children, Henrietta
and Dorotea, who’ve put up with my many long nights and “lost weekends” as I worked on this
book, and have been more patient than I could have hoped for; this book is dedicated to them.

www.it-ebooks.info

xv

Preface
I first encountered Cocoa as a college student in about 1989. Of course, that was before the
iPhone, before Mac OS X, and before it was even called Cocoa. Back then, the seed of today’s
Cocoa was a part of NeXTStep, the OS that was the core of the NeXT computers. NeXTStep was
years ahead of its time, and, while the lab full of NeXT workstations was woefully underused in
the computer science courses, my student sysadmin job had me using them daily. As a user, I was
hooked. I won’t dwell on the NeXT user experience here, but just state that many of the best
features of Mac OS X come not so much from the Mac of old as from NeXTStep.
At that time, there was no www, not much of a NeXTStep developer community, and very little
written about the development environment apart from the impenetrable tomes that NeXT
shipped with its earliest machines. I tried to wrap my head around Objective-C and the AppKit
from time to time, but without any nearby experts, or much example code to look at (not to

mention my actual studies which sometimes distracted me from playing with fun projects), I was
basically stumped.
After college, something completely unexpected happened. A friend pointed me in the direction
of a consulting firm in my city that was building custom NeXTStep apps for some pretty big
customers, and I had the good fortune to come on-board. Suddenly, I had a group of colleagues
who had not only been programming in NeXTStep for a while, some of them had even worked at
NeXT! All it took was a bit of their expert help to get me started, and the things that had seemed so
mysterious for years suddenly made sense. Within a few weeks, I learned so much I was able to
start leading some training and mentoring efforts in NeXTStep development.
The point of that isn’t that I’m a genius or a quick study. It’s that the set of technologies we now
call Cocoa are really powerful, and quite easy to learn and put to good use; but you’re likely to
need some help along the way. I’m hoping that this book will help nudge you in the right
directions, and help you learn the essence of Cocoa programming, so that, by the time you’re
finished reading it, you’ll have enough knowledge of Cocoa to be able to propel yourself forward
and write the Mac applications of your dreams. In short, the kind of book I wish I’d been able to
find 20 years ago.
Jack Nutting

www.it-ebooks.info
xvi

www.it-ebooks.info


1
1
Chapter
Must Love Cocoa
Welcome! You must be here because you want to write programs for your Mac. Well,
you’ve definitely come to the right place. (Here for Pilates? Third door down, on the

right.) By the time you finish this book, you’ll know everything you need to know to
create fast, efficient, good-looking Mac OS X applications.
The key to creating a modern Mac application is Cocoa. According to Apple, Cocoa is a
set of object-oriented frameworks that provide a runtime environment for Mac OS X
applications. As you make your way through this book, you’ll learn all about the Cocoa
frameworks and runtime environment. For the moment, think of Cocoa as a
programmer’s assistant that takes care of much of the housekeeping that goes along
with Mac development. Almost every common task performed by a Mac application,
from drawing a window to blinking the cursor in a text field, is handled for you when you
write programs using Cocoa, freeing you up to concentrate on the code that makes your
application unique.
Cocoa provides a class for just about every one of your development needs. There are
Cocoa classes for each piece of the Mac OS X user interface, from windows to menus,
scrollbars to buttons, images to icons. If you can think of a user interface element you’d
like to add to your own application, chances are very good that element is already
implemented as a Cocoa class.
Another benefit of using Cocoa is that it is tightly integrated with Mac OS X. Build your
application using Cocoa, and your application will play well with others and will interface
seamlessly with Mac OS X elements like the Finder and the Dock.
WHEN IS 20 YEARS NOT 20 YEARS?
Cocoa has been around in one form or another since 1986. The technologies that we call Cocoa evolved
from the NeXTStep AppKit, the application building tools developed for the NeXT platform. When Apple
bought NeXT in 1996, they began building a new version of the Mac OS, what we now know as Mac OS X,
basing much of the new operating system on technologies acquired from NeXT.
As Mac OS X evolved, so did Cocoa. Apple added technologies from the classic Mac OS, like QuickTime, as
well as completely new technologies, like the Quartz rendering system that enables all the fancy visual
1

www.it-ebooks.info
CHAPTER 1: Must Love Cocoa

2
effects and animation that OS X uses. They also made sure that they kept the Mac’s famed ease-of-use in
the process.
Bottom line: Cocoa is constantly evolving and expanding. The development tools, libraries, and frameworks
you’ll be learning in this book are the result of more than 20 years of experimentation and refinement.
Get a Mac and Download the Tools
Before you can begin creating applications with Cocoa, you’ll need a Macintosh
computer. It doesn’t have to be the newest or the most powerful Mac; in fact, pretty
much any Mac that’s been made in the last six or seven years or so will work just fine for
building the exercises in this book. As you become more serious about writing software,
you may find it’s worth investing in a newer or faster machine, but for now just about any
Mac made this millennium will work fine for learning what you need to learn. Any Intel-
based Mac, and almost all PowerPC Macs with a G4 or G5 processor will run Mac OS X
10.5 (Leopard). If you want to run the newer Mac OS X 10.6 (Snow Leopard), the
PowerPC machines won’t do; you’ll need to have an Intel machine.
You’ll also need to join Apple Developer Connection (ADC), which is Apple’s developer
relations organization. There are paid memberships, but the basic membership is free.
You’ll need at least the free membership in order to download Apple’s development
tools, which you’ll need to do in order to write software in Cocoa. To join ADC, open up
your web browser and navigate to If you already have
an Apple ID, press the Log in button and enter your info. If you are new to Apple’s online
services, click the register link and create your account.
Once you are a bona fide ADC member, you’ll be able to download Apple’s developer
tools. These tools are listed on the main Mac Dev Center page under the heading
Xcode. The link for downloading Xcode actually downloads a full suite of developer
tools, including all the software you’ll need for working with Cocoa.
Once you are logged in, find the version of Xcode that’s appropriate for your version of
Mac OS X, and click on the Xcode link to start the download. A .dmg disk image file will
download. Last we checked, the download was about a gigabyte, so it might take a few
minutes. Once it is done downloading, double-click the .dmg file to mount the disk

image. Next, double-click the installer file inside the disk image and start that install.
If you don’t have a high-speed internet connection, you may find the developer tools on
one of the CDs or DVDs that came with your Mac. That said, if possible, you should try
to find a way to download the latest version.
NOTE: If you’ve already installed the iPhone SDK, then you’re all set. When you install the
iPhone SDK on your computer, it also installs all the tools needed for creating Cocoa programs.
Though the frameworks do have major differences, the tools are pretty much the same, so if
you’ve done any iPhone SDK development, you should feel right at home creating Cocoa
programs.

www.it-ebooks.info
CHAPTER 1: Must Love Cocoa
3
Download the Source Code
In addition to downloading and installing Xcode, you’ll also need to download the
sample projects that go with this book. You can find the code archive on the Apress
Learn Cocoa on the Mac web page:

You’ll find the source code archive in the Book Resources area on the left side of the
page. Click the link, download the .zip archive, and move the Learn Cocoa Projects
folder to a location in your Documents folder.
You’ll also find a link on the Apress Learn Cocoa on the Mac web page, in the Book
Resources area, that lets you submit and view errata. If you find an error in the book
(much as we’d like to think otherwise, all books have errors) please do take a moment to
report the error. This will help us make the book better in subsequent printings. We
thank you in advance.
Getting Help
As you make your way through the book, you’ll no doubt have some questions you’d
like to get answered. Fortunately, there is a great community you can join, designed
specifically for this series of books. Check out:


Register with the site, find the appropriate book forum and post your questions. You are
sure to find other folks who can answer your questions and, who knows, after a while
you might find yourself answering questions for other folks as well.
What You Need to Know Before You Begin
This book assumes that you already have some basic programming knowledge. You
should be comfortable with the concepts of loops, variables, pointers, and linked lists.
This book also assumes that you understand the fundamentals of object-oriented
programming and are familiar with the Objective-C programming language. Starting with
Mac OS X Leopard 10.5, a new version of the language was introduced, called
Objective-C 2.0. Don’t worry if you’re not familiar with the more recent additions to the
Objective-C language. We’ll be sure to highlight any of the 2.0 language features we
take advantage of and explain how they work and why we are using them.
NEW TO OBJECTIVE-C?
Here are a few resources that will help you get started.
New to programming? Check out Learn C on the Mac, 4th Edition, written by our own Dave Mark:


www.it-ebooks.info
CHAPTER 1: Must Love Cocoa
4
New to Objective-C? Check out Learn Objective-C on the Mac, an excellent and approachable introduction
to Objective-C 2.0 by Mac programming experts Mark Dalrymple and Scott Knaster:

Next, navigate over to the Apple iPhone Development Center and download a copy of The Objective-C 2.0
Programming Language, a very detailed and extensive description of the language and a great reference
guide:

Are You Ready?
The Mac is a great computing platform, and Cocoa is the best tool to use to build your

Mac applications. If you are coming to the Mac from another platform, you may find it a
bit disorienting working with Cocoa and Objective-C. Even though you might find it hard
to get your bearings at first, as you make your way through this book, we’re confident
that you’ll soon start to wrap your head around the “Cocoa way” of doing things. With a
little perseverance, it will all start to make sense.
One thing you should keep in mind is that the exercises in this book are not simply a
checklist that, when completed, grant you Cocoa developer guru status. Every step of
the way, make sure you understand what you just did before moving on to the next
project. Don’t be afraid to make changes to the code. Experiment and observe the
results. That’s one of the best ways to wrap your head around the complexities of
coding in an environment like Cocoa.
Also, remember that we’ve set up a message forum for readers to discuss the exercises
and content of this book. So if you get stuck, or want to chat with us and other Cocoa
developers about any Cocoa programming topics, head over to
and register for the discussion forum.
That said, if you’ve got your developer tools installed, turn the page. If not, get to it!
Then let’s go!

www.it-ebooks.info


5
5
Chapter
Hello, World
As you’re probably well aware, it has become something of a tradition to call the first
project in any book on programming “Hello, World.” Following the “if it ain’t broke, don’t
fix it” guideline, we’ll stick with tradition.
Building “Hello, World”
By now, you should have Xcode installed on your machine. You should also have the

Learn Cocoa Projects folder ensconced, safely, somewhere on your hard drive. If by
some set of circumstances you don’t, go directly to Chapter 1 (do not pass Go, do not
collect $200) and reread the appropriate sections.
The first project we’ll be working with is located in the 02.01 – Hello, World folder.
Launch Xcode, which is located in the folder /Developer/Applications. Just in case
you’ve never used Xcode before, we’re going to walk you through the process of
creating a new project.
Start by selecting New Project… from the File menu, or by typing N. When the New
Project Assistant comes up (see Figure 2–1), select Application from under the Mac OS
X heading in the left column, then select the Cocoa Application icon from the upper-right
pane and press the Choose… button.
2

www.it-ebooks.info
CHAPTER 2: Hello, World
6

Figure 2–1. Selecting the Cocoa Application project template from Xcode’s New Project Assistant
You’ll be prompted for a project name and save location using the standard save sheet
(see Figure 2–2). Type in the project name of Hello World. You can choose to save the
project in your Documents folder, or you can create a separate folder to hold the Xcode
projects that you build yourself. It really doesn’t matter where you save an Xcode
project, but you may find it easier to find them later if you pick one place and always
save your projects there.

Figure 2–2. Naming your project and selecting the save location
Once you select a filename and location, a new project window will appear (as shown
in Figure 2–3). Although you might already be familiar with Xcode, let’s take a second to

www.it-ebooks.info

CHAPTER 2: Hello, World
7
look at the project window. This is where we will be spending an awful lot of our time, so
we want to make sure we’re all on the same page.

Figure 2–3. Your project’s main window in Xcode
Your project window features a toolbar across the top, which gives you ready access to
a bunch of commonly used commands. Below the toolbar, the window is divided into
three main sections, or panes.
The pane that runs down the left side of the window is called the Groups & Files pane.
All of the resources that make up your project are grouped here, as are a number of
relevant project settings. Clicking on the little triangle to the left of an item expands that
item to show any available sub-items. If you click on the triangle to the left of an
expanded item, you will hide its sub-items.
The top right pane is called the Detail View and shows you detailed information about
items selected in the Groups & Files pane. If nothing is selected in the Groups & Files
pane, the Detail View shows all the files that make up your project. The lower right pane
is called the Editor pane. If you select a single file in either the Groups & Files pane or
the Detail pane, and Xcode knows how to display or edit that kind of file, the contents of
the file will be displayed in the Editor pane. This is where you will be writing and editing
all of your application’s source code.

www.it-ebooks.info

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×