Learning Cocoa with Objective-C/Preface
|Learning Cocoa with Objective-C|
Like a finely tuned BMW, Mac OS X is the ultimate programming machine.
Under the hood lies a powerful Unix engine, named Darwin, developed via Apple's open source initiative and based on FreeBSD 4.4 and the Mach 3.0 microkernel. On the outside is a highly polished graphical user interface (GUI) whose usability can't be touched by any desktop environment on the planet, including GNOME and KDE for Linux, as well as Windows XP.
The newest cat on the block—Mac OS X 10.2 (code-named Jaguar)—takes desktop and network computing to a new level. Jaguar, first introduced to developers as a pre-Alpha release at Apple's Worldwide Developer Conference (WWDC) in May 2002 and later released to the public on August 24, 2002, brings many changes and improvements to the legacy set forth by the previous Mac OS X releases. These changes include several additions to the Cocoa application programming interfaces (APIs), known as the Cocoa frameworks, arguably the best GUI application development environment on the face of the planet. An integrated set of libraries and runtime, Cocoa provides a rich infrastructure on which to build great user applications.
When it comes to building Cocoa applications, developers can choose from three languages to work with the Cocoa APIs: Objective-C, Java, and AppleScript. This new edition of Learning Cocoa, retitled as Learning Cocoa with Objective-C and thoroughly revised and updated for Jaguar, shows you how to get started with building Cocoa applications for Mac OS X using the Objective-C binding to the Cocoa frameworks.
As an introductory book on Cocoa development, Learning Cocoa with Objective-C accomplishes the following:
- Introduces you to the concepts of object-oriented programming with Objective-C
- Shows you how to use Apple's Developer Tools, in particular, Project Builder and Interface Builder
- Introduces you to Cocoa's frameworks—Foundation and the Application Kit—by having you build simple applications along the way
The concepts learned in one chapter spill over to the next, and the sample programs you build while reading along get more complex as you go deeper into the book. By the end of the book, you will have learned enough about Cocoa and Objective-C to set you on your way to higher learning, and for that, there are plenty of other books available:
- Building Cocoa Applications: A Step-by-Step Guide , by Simson Garfinkel and Michael K. Mahoney (O'Reilly & Associates, Inc.)
- Cocoa Programming for Mac OS X, by Aaron Hillegass (Addison-Wesley)
- Cocoa Programming, by Scott Anguish, Erik Buck, and Donald Yacktman (Sams)
While these books also deal with Cocoa programming with Objective-C, each book takes a slightly different approach. Programming is a funny art, and sometimes it is invaluable to see several approaches to the same subject matter. To be a true master of the craft, you'll probably want to read each of these books and glean from each what you can.
In addition to this and the previously listed books, you also have a vast resource of information at your fingertips in the form of Apple's own documentation. Installed on your system along with the Developer Tools, Apple's docs can be found in /Developer /Documentationin both PDF and HTML format. If you have a fast or constant link to the Internet, you can save some space on your hard drive by dumping these docs in the Trash and using the online documentation found at http://developer.apple.com.
When Apple updates their documentation, they often first post the revisions online, so you might want to keep that URL handy.
Additionally, there are some online resources—mailing lists and web sites—that you should subscribe to and read frequently. A listing of these resources can be found in Appendix B, located at the back of this book.
As the title implies, this is a "Learning" book—a book for newcomers to Cocoa and Objective-C. This book assumes you have a basic knowledge of ANSI C and that you're open to learning the concepts of object-oriented programming. If you're not familiar with C and you haven't programmed with Java or some other compiled language, you might want to hold off on reading this book just yet. Likewise, if you're already familiar with Objective-C or have programmed for NeXTSTEP, chances are this book will be too basic for your liking. Not that you can't pick something up from reading it, but this book is better suited for newcomers.
Who Should Read This Book
As mentioned earlier, this book was written for programmers who are interested in learning how to develop Cocoa applications using the Objective-C language. It assumes that you have some experience with C programming, as well as a basic understanding of computer-science concepts. If you're familiar with C or Java, you should have no problem picking up Objective-C.
Who Should Not Read This Book
Of course, one book can't be everything to everyone. Some people will find this book too basic or too advanced for their liking. For example:
- Novice programmers
- If you have never programmed before and want to learn the basics of programming, you should start off reading an introductory programming text. To learn C, the language upon which Objective-C is based, we recommend the following books:
- The C Programming Language , by Brian W. Kernighan and Dennis M. Ritchie (Prentice Hall)
- Practical C Programming, by Steve Oualline (O'Reilly)
These books will introduce you to the concepts of programming with C, giving you the foundation you need before reading this book.
- Experienced NeXT developers
- If you have worked with OpenStep or NeXTSTEP, you will probably find the material in this book too basic. You might use this book as a refresher to come up to speed, but it probably won't be the Nirvana you're searching for.
- Java developers
- This book covers Cocoa using the Objective-C language. If you are a Java developer and don't mind learning a new language (learning new languages is always good for you!), then you will do fine with this book. However, if you want a strict treatment of Cocoa with Java, this book is not for you.
What You Need to Know
Extensive programming experience is not required to complete the examples in this book. Since the Objective-C language is a superset of ANSI C, experience with the C programming language is helpful. If you have experience with an object-oriented programming language such as Java or Smalltalk, you should find the concepts of Objective-C easy to comprehend. If you don't have experience with object-oriented concepts, don't worry; we will try our best to guide you through the terminology and to give you pointers to other texts and reference material.
No prior experience programming on Mac OS X is necessary to complete the tutorials in this book. We'll show you how to use the Developer Tools that come with Mac OS X and show you how to build your first Cocoa application in no time.
At some point you should explore the wealth of developer documentation that Apple installs with the Developer Tools. This documentation covers the Mac OS X system architecture, developer tools, release notes, the Objective-C language, the Cocoa API references, and so on. There are four places you can access Apple's developer documentation:
- The /Developer/Documentationfolder on your system. Specifically, most of the Cocoa documentation is located in the /Developer/Documentation/Cocoafolder.
- The Help menu in Project Builder (/Developer/Applications), which is one of the development tools you will use as you work your way through this book.
- Mac Help from the Finder. After launching Mac Help and clicking on the "Help Center" toolbar item, you'll be able to find the Developer Help Center link.
- Online at http://developer.apple.com. As mentioned earlier, Apple often posts updates to its documentation online first, so you should check here if a document on your system doesn't have the answer for which you're looking.
About the Example Code
You will find many examples in this book. The code for these examples is contained within the text, but you may prefer to download a disk image (.dmg ) of the examples rather than typing all that code in by hand. You can find the code online and packaged for download at http://www.oreilly.com/catalog/learncocoa2. You may also want to visit this site for any important notes or errata about the book.
All of the examples have been tested using Mac OS X 10.2, Project Builder 2.0, and Interface Builder 2.1. If you use this book with a later release of any of these products, the user interface and features may be different from those shown in the book, but everything should work. However, because the examples utilize many features first introduced with Jaguar, such as GCC 3 and the AddressBook APIs, you should not use an earlier release of Mac OS X with this book.
In some of the examples, we put a number (or letter, depending on the other elements on the page) on the right side of any line of code that we explain in detail. Numbered explanations appear below a listing, as shown in the following example:
int row = [itemList selectedRow]; // 1 NSString * newName = [[itemList selectedCell] stringValue]; // 2
- The index of the row is obtained by passing the selectedRow message to the itemList object.
- The newName string is obtained from the cell by using the stringValue message.
How This Book Is Organized
This book consists of 17 chapters and 3 appendixes, organized into 5 parts. The first three parts are organized so that each chapter builds upon the previous one. You should start at the beginning and proceed sequentially until you've read through the last chapter.
Most chapters contain example applications for you to work through, as well as exercises that build upon the material covered. Each chapter's applications and exercises are self-contained and do not spread across chapters.
Cocoa Overview and Foundation introduces the Cocoa frameworks and describes the high-level features they provide application programmers, as well as how they fit with other Mac OS X frameworks. It also includes a brief introduction to object-oriented programming, the Objective-C language, and Apple's development tools.
- Chapter 1
- Places Cocoa in the context of the Mac OS X programming environment and introduces the frameworks and classes that make up the Cocoa API.
- Chapter 2
- Introduces Project Builder and Interface Builder, Apple's tools for Mac OS X development. The chapter then goes on to describe the wide array of tools and utilities available to assist in building, debugging, and performance-tuning applications on Mac OS X.
- Chapter 3
- Explains the benefits of object-oriented programming practices (as compared to procedural programming) and provides an introduction to the terminology and core concepts needed to use the Cocoa frameworks effectively. It also includes a primer on the Objective-C programming language.
- Chapter 4
- Provides a series of mini-tutorials to introduce the Cocoa Foundation, including strings, arrays, collections, utility functions, and memory management.
Single-Window Applications covers the basic building blocks of any Cocoa application that displays a single GUI window to the user. This section uses a series of examples to illustrate the concepts presented. The techniques and concepts you learn in each chapter will lay the foundation for the next chapter.
- Chapter 5
- Introduces the Model-View-Controller (MVC) pattern and how Cocoa programs are structured and developed. You will also learn about nib files and how to use them in your applications.
- Chapter 6
- Goes into detail about how the windowing system works, as well as how to create View and Controller objects to present a user interface.
- Chapter 7
- Cocoa's default set of controls covers most of the common UI needs that applications have, but they can't cover everything. Your application may need to present a specialized view onto a data source or simply draw arbitrary content to the screen. This chapter shows how to create these custom views.
- Chapter 8
- Introduces the event loop and explains how events propagate along the responder chain. It also covers how events are queued and dispatched, as well as how event delegation works.
- Chapter 9
- Shows how to work with the data-bearing objects of an application. The chapter also shows how this information can be utilized with the Controllers and Views of an application and how it can be read from and written to storage.
Many applications today, such as word processors and web browsers, are built around the concept of a document. Creating an application that can handle multiple documents is tedious in the best of times. Luckily, Cocoa provides the ability for an application to handle multiple documents with ease. Document-Based Applications shows how to use Cocoa's document architecture.
- Chapter 10
- Presents the basic concepts of the document-handling architecture and how documents are managed. The chapter guides you through the process of creating an application that takes advantage of the architecture.
- Chapter 11
- Shows advanced text-handling abilities of Cocoa, such as handling fonts, working with layout managers, enabling rulers, and working with attachments.
Miscellaneous Topics covers a variety of Mac OS X and Cocoa features that are important to delivering finished applications and giving them their finishing touches. The chapters in this part of the book cover diverse topics and can be read in any order.
- Chapter 12
- This chapter shows you how to add printing functionality to your application.
- Chapter 13
- Here we describe how bundles, application or otherwise, are structured, how icons and document types are defined, and how application signatures work.
- Chapter 14
- Once you build an application, there are several ways to customize the interface to accommodate users in different parts of the world.
- Chapter 15
- Mac OS X provides comprehensive management of user preferences. This chapter explains how to work with this system to store information that can be used across multiple invocations of your application.
- Chapter 16
- Applications will often have more than just one interface component. Inspectors and palettes abound in modern applications. This chapter shows in detail how to store your user interface in multiple nib files to improve performance and ease maintainability and localization.
- Chapter 17
- Once you build an application, there are several important things you should do to make it ready for distribution. Cocoa provides default copyright strings and About boxes that need to be edited, and you should probably create some sort of Help documentation for the application. Finally, this chapter shows how to create an icon for your application and add that to the application bundle as well.
The Appendixes include quick-reference material for learning more about Cocoa's Objective-C classes and list resources that are beyond the scope of this book for expanding your Cocoa development horizon.
- Appendix A
- Provides solutions to all of the exercises found at the end of each chapter.
- Appendix B
- Provides a valuable list of Cocoa-related resources and where to find them, including Mac OS X's "built-in" developer documentation, books, mailing lists, and web sites.
- Appendix C
- Provides a guide to the various API references available to you as a developer, as well as some tools that will help you search and browse the available documentation.
How to Use This Book
Our recommendation is that you read this book from cover to cover, particularly if you're new to Cocoa and need to learn more about object-oriented programming (OOP). As you read through the book, you should work on the sample programs along the way. Doing so will give you the foundation you need to understand what Objective-C is (and isn't) and the concepts of OOP, most notably the MVC paradigm that aids in GUI application design. We try to take the approach of teaching you small things first and then building on those small concepts throughout the rest of the book.
If you have experience with Java or Smalltalk, we recommend that you read this book from front to back as well. Since you have experience with object-oriented concepts and programming, there are some sections that you will be able to skim. However, be careful not to skim too fast, as you might miss some important details.
Conventions Used in This Book
The following is a list of the typographical conventions used in this book:
- Used to indicate new terms, URLs, filenames, file extensions, directories, commands and options, program names, and to highlight comments in examples. For example, a path in the filesystem will appear as /Developer/Applications.
- Constant Width
- Used to show code examples, the contents of files, or the output from commands.
- Constant Width Bold
- Used in examples and tables to show commands or other text that should be typed literally.
- Constant Width Italic
- Used in examples and tables to show text that should be replaced with user-supplied values.
- Menus and their options are referred to in the text as File → Open, Edit → Copy, etc. Arrows are used to signify a navigation path when using window options; for example, System Preferences → Login → Login Items means that you would launch System Preferences, click the icon for the Login control panel, and select the Login Items pane within that panel.
- Pathnames are used to show the location of a file or application in the filesystem. Directories (or folders) are separated by a forward slash. For example, if you see something like, " . . . launch Project Builder (/Developer/Applications)" in the text, that means that the Project Builder application can be found in the Applicationssubdirectory of the Developerdirectory.
- A carriage return ([[Image:Learning Cocoa with Objective-C_I__tt6.png|]]) at the end of a line of code is used to denote an unnatural line break; that is, you should not enter these as two lines of code, but as one continuous line. Multiple lines are used in these cases due to printing constraints.
- %, #
- The percent sign (%) is used in some examples to show the user prompt from the tcsh shell; the hash mark (#) is the prompt for the root user.
- Menu Symbols
- When looking at the menus for any application, you will see some symbols associated with keyboard shortcuts for a particular command. For example, to create a new project in Project Builder, you would go to the File menu and select New Project (File → New Project), or you could issue the keyboard shortcut, Shift-[[Image:Learning Cocoa with Objective-C_I__tt7.png|]]-N.
You should pay special attention to notes set apart from the text with the following icons:
This is a tip, suggestion, or general note. It contains useful supplementary information about the topic at hand.
This indicates a warning or caution. It will help you solve and avoid annoying problems.
How to Contact Us
We have tested and verified the information in this book to the best of our ability, but you may find that features have changed (or even that we have made mistakes!). As a newcomer to Cocoa and a reader of this book, you can help us to improve future editions by sending us your feedback. Please let us know about any errors, inaccuracies, bugs, misleading or confusing statements, and typos that you find anywhere in this book.
Please also let us know what we can do to make this book more useful to you. We take your comments seriously and will try to incorporate reasonable suggestions into future editions. You can write to us at:
O'Reilly & Associates, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 998-9938 (in the U.S. or Canada)
(707) 829-0515 (international/local)
(707) 829-0104 (fax)
You can also send us messages electronically. To be put on the mailing list or to request a catalog, send email to:
To ask technical questions or to comment on the book, send email to:
The web site for Learning Cocoa with Objective-C, Second Edition lists examples, errata, and plans for future editions. You can find this page at:
For more information about this book and others, see the O'Reilly web site:
First and foremost, I'd like to thank my editor, Chuck Toporek, who talked me into writing the new edition of this book (twice even) and alternately utilized the editor's whip and kind words of encouragement to guide me toward its completion. Without him, his advice, and his faith in me to get the job done, this book would not have happened. Also at O'Reilly, I'd like to thank Jeff Holcomb, the copyeditor for this book; David Chu, who assisted Chuck in pulling this book together for production; Brenda Miller, who produced the index; Derrick Story, who encouraged my early efforts with Cocoa by letting me write for the O'Reilly Network; and finally Tim O'Reilly, Michael Loukides, and Bob Eckstien, who always knew that I would write a book for O'Reilly & Associates some day.
Thanks as well to all the people at Apple, especially to the original NeXT and Apple documentation teams. For this new edition, we've changed the title, stripped the book down to bare metal, and built it back up. Without the foundation provided by the original documentation teams, the job would have been much harder. Also thanks to the many Cocoa engineers at Apple for taking the time to hash over the outline for the revision, and for reviewing drafts of the manuscript along the way. You guys know who you are.
Many thanks to the independent reviewers of this book, including Jo Davidson (who gave up part of the Memorial Day weekend to help us meet our deadlines) and Mike Barron.
Special thanks to Jason Hunter, who gave me an author's insight into the writing process, for helping me find the right metaphors in Chapter 3, and for always being there when needed. In addition, many thanks to Wilfredo Sánchez Vega, who got me hooked on Mac OS X in the first place after my Windows laptop went through one of its periodic meltdowns.
Music from many creative and talented people fueled the writing of this book. Among the artists in heavy rotation in iTunes and on the iPod: Tori Amos, Bedrock, Blue Man Group, BT, The Chemical Brothers, The Crystal Method, Darude, DJ Amber (from the San Francisco Bay rave scene), DJ Dragn'fly (from the Sacramento rave scene), Brian Eno, Fatboy Slim, The Future Sound of London, Juno Reactor, Moby, New Order, The Orb, Orbital, Mario Piu, Prodigy, Rinocerose, Sasha, Squarepusher, Underworld, Paul van Dyk, and many others.
And finally, thanks to all my family and friends who lent support to the book writing process and who encouraged me to chase my dreams: Dad, who taught me everything I needed to know after all; Mom, who brought me into the world; Mahaila, who probably never expected that I—of all the people in the family—would write a book; my sisters Susan, Illona, Joli, and Heather, as well as my friends Justyna Horwat and Jim Driscoll. Last, but not least, I want to thank Eleo, who ended up thoroughly addicted to the wireless network I installed at her place so that I could work on her couch, tapping away on my Titanium PowerBook until late in the night.
- ↑ Learn the ways of the Force, Luke—just stay away from the Dark Side.
- ↑ This book does not come with a CD-ROM. Bundling a CD would increase the cost of production and the cost to you. It is our belief that anyone reading this book has access to an Internet connection and would rather save money by simply downloading the example code off the Web.
- ↑ GCC 3 introduces support for the C 99 standard, allowing us to make our example code more readable and easier to understand.