Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Introduction

Introduction

Cocoa Recipes for Mac OS X is a cookbook for developing Macintosh computer applications using the Objective-C programming language in the Mac OS X Cocoa environment. The first edition was written for Mac OS X 10.2 Jaguar. This second edition covers features that are new in Mac OS X 10.6 Snow Leopard as well as the several older versions of the Macintosh operating system that have been released since Jaguar.

To use Vermont Recipes to create the Vermont Recipes 2 application that forms its basis, you must install Snow Leopard and the Mac OS X developer tools for Snow Leopard on your computer. Because Snow Leopard does not run on PowerPC Macs, your development computer must be an Intel-based Mac. The finished Vermont Recipes 2 application nevertheless runs both on PowerPC and Intel computers running Mac OS X 10.5 Leopard and on Intel computers running Leopard or Snow Leopard. When Vermont Recipes 2 runs under Leopard, of course, it can’t use the new Snow Leopard features described in this book.

The book is subtitled The Vermont Recipes because it had its origin on a Web page of that name. The publisher of the original Web edition, Stepwise, was located in Vermont, and the author lives in Vermont. The Vermont Recipes Web page was the first in-depth third-party tutorial about Cocoa, and many of today’s Cocoa developers got their start with it.

The book takes a practical, no-nonsense, hands-on, step-by-step approach, walking you through the details of building a Macintosh application from start to finish using the Objective-C programming language and the Cocoa frameworks. It explains in detail what the code is doing and why it works, with only as much theory about the programming language and the frameworks as is needed to understand the approach taken. Vermont Recipes places a decided emphasis on getting an application to work correctly as quickly as possible.

About Vermont Recipes

Vermont Recipes is distinguished from other Cocoa books and tutorials by its single-minded dedication to creating a complete, integrated, working application. It approaches the job of writing a Cocoa application just as you would approach it in real life, starting where you would start, progressing through the steps that you would follow, and finishing up where you would end. It does not jump from one example to another to illustrate different features of the programming environment. Nor is it organized topically with a multitude of isolated discussions of narrow features of Objective-C and the Cocoa frameworks taken out of context. One advantage of the Vermont Recipes approach is that you learn how to organize an application’s files and to cope with application-wide interactions that are easily overlooked in a more fragmentary presentation.

The second edition carries this approach even further than the first edition. At the time of the first edition, there was relatively little information available about Cocoa, and the book therefore devoted a lot of space to the details of coding individual user interface elements. With the passage of several years, Apple documentation and third-party books and Web sites have amply covered topics like that. The second edition therefore does not focus on such details but instead covers them in passing as needed to write the Vermont Recipes application.

Once you’ve finished Vermont Recipes, you will be able to follow the same sequence of steps to write a full-featured application of your own. Think of Vermont Recipes as a detailed cookbook for a magnificent banquet, and enjoy the many other excellent Cocoa programming books that have appeared as appetizers, side dishes, and desserts, as your taste dictates.

The emphasis here is on code. Vermont Recipes is not a tutorial on the finer points of Apple’s development tools, Xcode and Interface Builder, although the steps necessary to create an application are discussed in more than enough detail to get you through the job. Nor does it explain all of the niceties of Objective-C syntax. Instead, it offers discussions of important features of the language, such as categories and protocols, in the Cocoa context, as they are encountered in the developing application. It is an ordered collection of do-it-yourself recipes—ingredients consisting of commented and organized code snippets, together with instructions for assembling them into a working whole—to guide you through the process of creating classes and subclasses, objects, properties, outlets, actions, and all the other pieces, until you have built a fully functional Cocoa application.

Vermont Recipes is a cookbook, but it doesn’t include the kitchen sink. The Cocoa frameworks and related libraries and frameworks contain hundreds of classes, and this book makes no attempt to show you how to use all of them. What it does do is show you how the most important of them can be used to create a complete, working application with controls of many kinds and other common application features. It also attempts to teach you, by example and explanation, most of the more general concepts and techniques that are used in Cocoa and Objective-C programming. In combination, what you learn from this book should take you a long way toward an enhanced level of understanding, so that you will find it much easier to master other Cocoa classes on your own.

There is no one right way to design or code a Cocoa application. Vermont Recipes takes an approach that works, that is relatively easy to learn, that is consistent and therefore easy to maintain and enhance, and that is sufficiently general to adapt easily to a variety of scenarios. It conforms to conventional Cocoa practices and nomenclature. The application you build here is a document-based application using Cocoa’s Application Kit and Foundation frameworks, which gives it the flexibility and power to serve as a model for the widest variety of applications. Using the AppKit gives you a large part of the normal, expected functionality of any Mac OS X application “for free,” without requiring any coding on your part. Conforming to the conventions of the AppKit also guarantees you the greatest freedom to add Cocoa technologies to your application as they become available, with a minimum of rewriting.

An important advantage of Vermont Recipes stems from the fact that I began writing it while I was learning Cocoa myself during the heady days of the first Mac OS X developer previews—through careful study of Apple’s initially sparse documentation and sample applications; online assistance from the NeXTstep, OpenStep, Rhapsody, and Cocoa developer community; and trial and error. It therefore covers ground that I know from personal experience would confuse and frustrate a Cocoa beginner if not spelled out in some detail. A Cocoa developer with longer experience might take many issues for granted and therefore neglect to cover them. At the same time, this second edition is based on six additional years of experience writing a number of Cocoa applications, including two commercial applications.

The initial, Web-based version of Vermont Recipes was written for the Mac OS X developer previews and Mac OS X 10.0 Cheetah in 2000. The first printed edition was written for Mac OS X 10.2 Jaguar, released in 2002. Apple released Mac OS X 10.6 Snow Leopard in 2009. The code in this second printed edition of the book works with Mac OS X 10.5 Leopard as well as Snow Leopard.

All Macs that have shipped in the last several years include the latest version of the developer tools as of the date of the system-installation DVD that ships with the computer, so you can install them yourself at no extra cost. Free updates become available from Apple periodically. They are also available as part of the retail Mac OS X product, in case you bought your Mac before Snow Leopard and its upgraded developer tools were available.

The recipes in the book target people who have some programming experience. The book assumes only a modest grounding in the C and Objective-C programming languages and at least a little familiarity with object-oriented programming concepts. Both of these can be gained by reading one or two of the many widely available introductory programming texts about C and object-oriented programming, as outlined in Section 1 of this book. No prior experience with Cocoa’s predecessors, NeXTstep, OpenStep, and Rhapsody, is necessary, nor is any knowledge of Unix required. You don’t need to know Java or C++, and some even say that knowledge of C++ is a hindrance because of the habits you must unlearn.

Only a limited exposure to Objective-C is needed. Objective-C is nothing more than standard C with a few object-oriented extensions. Once you know C’s commonly used features, you can learn the Objective-C extensions in a day or two. Having to learn a new programming language is not the obstacle to using Cocoa that some may perceive it to be.

Why Cocoa?

Apple understandably emphasized Carbon development when it initially rolled out Mac OS X, to encourage rapid migration of existing Classic applications from Mac OS 9 to Mac OS X. The Carbon application environment, while complex, allowed those with a longstanding investment in knowledge of the Mac OS toolbox to bring their applications to Mac OS X easily while maintaining compatibility with Mac OS 8 and 9. Apple’s strategy paid off, with virtually every major Macintosh application quickly becoming available in native Mac OS X form.

Apple soon positioned Cocoa as the “real” Mac OS X of the future, and it cemented that decision when it announced that it was dropping support for the user interface aspects of Carbon. The company has repeatedly urged developers of new Mac OS X applications to develop them using the Cocoa frameworks. These are mature and powerful application frameworks based on years of NeXTstep and OpenStep experience and the ensuing years of Cocoa. They incorporate virtually all of Mac OS X’s functionality and the distinctive appearance of its user interface.

Experienced developers report that the Cocoa frameworks reduce development time by a very substantial factor. This is partly because the frameworks are so complete, giving you a vast amount of functionality without any effort on your part. Apple’s Cocoa engineers are fond of demonstrating that you can build a reasonably powerful text editor using the Cocoa frameworks—complete with multiple windows that have scrolling views, a working Fonts panel, copy and paste, drag and drop, unlimited undo and redo, as-you-type spell checking, and other useful features—all simply by assembling prebuilt features in Interface Builder without having to write a single line of code.

Another factor that makes Cocoa development so efficient is Cocoa’s use of powerful design patterns not found in many other environments. For example, a number of the Cocoa classes employ the concept of delegation, where the system automatically calls a method of a delegate object when a significant event takes place, such as the user’s attempting to close a window. You write the delegate method yourself, or you decide not to implement it at all, which allows you to decide whether and how your application should respond. These hooks, liberally sprinkled throughout the Cocoa frameworks, let you customize application behavior by performing additional actions or vetoing actions that the system proposes to take, depending on conditions that exist at run time. You usually do not have to subclass the built-in Cocoa AppKit classes to gain the benefit of these optional but powerful features. Many of the Cocoa classes also post notifications, so that any of your objects can learn of events as they occur elsewhere in the system and deal with them appropriately. It is vital that you learn these and other features of the hundreds of classes that make up the Cocoa frameworks. While they present a substantial learning curve, these and others, like protocols and categories, facilitate an extraordinarily productive development experience.

Initially, the classes of the Cocoa frameworks fell into two groups, the Application Kit and Foundation, and these two umbrella groups still form the core of the Cocoa frameworks. Foundation focuses on basic data types, system functionality, and other matters having nothing to do with the user interface. The AppKit concentrates on the user interface and other application features such as documents. Over the years since Mac OS X was introduced, additional Objective-C classes have been added to the mix, to the point where developers no longer agree on which of them are properly considered part of Cocoa and which are non-Cocoa classes that happen to be written in Objective-C instead of procedural C. The distinction no longer matters except to purists, because system-level and Carbon APIs written in C, as well as the new Objective-C classes, can be freely intermixed in program code without difficulty. Developers continue to speak of the Cocoa frameworks only as convenient shorthand for code that is centered on Foundation and the AppKit and their associated design patterns.

Many of the Foundation classes abstract the operating system, making it easy, for example, to deal with files and networking at a high level without losing access to any of the power of a lower-level approach. Others provide programming features that are always needed, such as object-oriented collection classes and data types. The NSString class, for example, is used throughout Cocoa to handle character-based data, bringing automatic support for Unicode text handling, for conversion to and from different text encodings, and for internationalization and localization.

The AppKit provides classes for implementing windows, all manner of user controls, menus, and all of the other features you need to provide a complete user interface. You can subclass all of these to create custom controls and views, if you wish. The AppKit also provides fundamental classes that support writing a fully integrated, document-based application, including NSApplication, NSDocument, and NSWindowController, which you will learn much about in Vermont Recipes.

Why Objective-C?

You can use other programming languages, such as Objective-C++, Ruby, Python, and even AppleScript, for Cocoa development, but most Cocoa developers seem to prefer Objective-C. At one time it was common for developers to question whether Objective-C, which uses a runtime system to dispatch messages, was fast enough for many purposes, compared with Carbon and system-level C APIs. These debates about speed have largely evaporated with the advent of faster computers, although there remain legitimate reasons to optimize code for speed in rare instances where profiling demonstrates the need. Objective-C 2.0, introduced recently, includes new features that improve execution speed in certain circumstances, such as for loops.

Vermont Recipes is based almost solely on Objective-C. Objective-C is a surprisingly easy language to learn if you already know C, because it is in fact standard ANSI C with a small number of object-oriented additions. Choosing to develop Cocoa applications in Objective-C may therefore be motivated by nothing more than the wish, for C programmers, to avoid the substantial investment of time required to learn a fundamentally new language.

There are more substantial reasons to use Objective-C, however. Objective-C’s dynamic object-oriented extensions to standard C are flexible and powerful, making it possible to design applications in ways that are difficult or impossible using more traditional static programming languages such as C++. Dynamic means, among other things, that Objective-C methods are bound at run time under the control of your code, so you don’t have to anticipate the details of a user’s actions and lock in your responses at compile time. Instead, your code can respond at run time with a level of flexibility that is not available in other languages. It also means that you are able to use introspection, inquiring at run time about the capabilities of any Objective-C object (for example, whether it implements a particular method). You can do such things as assign method selectors to variables and hand them around at run time for execution by name in response to current conditions.

Developers learning Objective-C often report that they have experienced a magical “Aha!” moment, when their understanding of the language jells and wide new horizons of possibility suddenly become visible.

Naming Conventions

Vermont Recipes follows the naming conventions of Objective-C as they have grown up around NeXTstep and its successors. Some of these conventions—particularly the naming of accessor methods—are actually required in order to take advantage of built-in features of the Cocoa development and runtime environments. Others are work habits that have become more or less generally accepted in the Objective-C and Cocoa communities because they make it easier for other developers to read your code. The following are the most common rules.

  • Give a method that gets the value of an instance variable the same name as the variable it accesses. For example, method myName gets the value of variable myName.

  • Give a method that sets the value of a variable a name beginning with set followed by the name of the variable with an initial capital letter. For example, method setMyName: sets the value of variable myName.

  • Start method and instance variable names with a lowercase letter; for example, init.

  • Start class, category, and protocol names with an uppercase letter; for example, MyDocument.

  • Prefix class names, exported or global variable names, notification names, and defined types with two or three distinctive letters to avoid contaminating the global name space and running into naming conflicts with other software. For example, use VR for some of the Vermont Recipes classes and NS for most of the Apple Cocoa classes.

For more information about Cocoa naming conventions, read Apple’s Coding Guidelines for Cocoa, available on your computer in the Xcode Developer Documentation window.

Apple informally reserves to itself the use of a leading underscore character (_) when naming private methods and exported functions. Developers who also use this naming convention, as some do, risk unknowingly overriding private methods in Apple’s frameworks, with unfortunate consequences. Apple also uses the leading underscore for private instance variables, but the compiler will catch instance variable naming conflicts in your code.

Newcomers to Objective-C should also be aware of the correct way to identify a method. An Objective-C method can be uniquely identified and accurately distinguished from similarly named methods only if its name, all of its parameter labels, and the colons that separate them are included (some methods take no parameters, so they have no colon). Collectively, these compose the method’s name or signature.

For example, the -close method is different from the -close: method. It would be incorrect and misleading to refer to either of these as a close method. This is not only an authoring guideline but also a feature of the language. You often use a method’s signature in code in ways that are not common in other programming languages, and your code will malfunction if you do not heed this advice.

A leading minus sign (-) or plus sign (+) before a method name distinguishes instance and class methods in their declarations and implementations, but you do not include them when invoking a method in code. The leading sign is sometimes omitted when writing about methods (as the first edition of this book did), but you must be aware of the difference between instance and class methods.

While on the subject of naming conventions, what about the proper capitalization of NeXT and NeXTstep? Yes, the official name of the company where Cocoa’s lineage got its start was NeXT Computer, Inc., and the official name of the product was NeXTstep. Although NeXT, and now Apple, registered trademarks in these names as shown here, it also claimed trademarks in the more ordinary forms Next and NextStep. You see either form, and others, in use today.

Apple’s Cocoa Documentation

Throughout this book, I collect references to official Apple documentation and sample code providing additional information about the topic at hand. To make them easier to find, these collections all have the title Documentation and the same distinctive appearance. Once you have installed the developer tools on your computer, most of the Apple documentation mentioned in this book can be found on your computer by searching the Xcode Documentation window for the name of the document as given here. The documentation is also available on Apple’s Developer Web site at http://developer.apple.com/mac/library/navigation/index.html. Occasionally, I also collect third-party articles, books, and blog entries, with information about where to find them.

Xcode and Interface Builder

Cocoa applications are now almost universally written and built using Apple’s principal developer tools, Xcode and Interface Builder. Xcode is today’s counterpart of the original Mac OS X Integrated Development Environment (IDE), Project Builder. It handles such tasks as editing, compiling, debugging, and linking code, all under one roof.

A Cocoa beginner may perceive Interface Builder to be nothing more than a convenient interactive graphical user interface (GUI) design utility and Xcode to be the tool for building an application. This perception would be inaccurate, but in Vermont Recipes you nevertheless learn how to use Xcode to create a new project and to write its code. Interface Builder is mainly used as a utility to design, build, and test the GUI, but not to generate significant amounts of code. Interface Builder’s Read Class Files and Reload All Class Files commands may sometimes be used to update the internals of the Interface Builder nib files when outlets and actions have been added, deleted, or modified in the source code. But Interface Builder is rarely used to generate code using its Write Class Files command, and then generally only for prototyping the initial elements of a new class.

You will discover that the nib files that Interface Builder generates are an integral part of a Cocoa application. A nib file embodies an application’s user interface more comprehensively than a simple design tool would. Interface Builder allows you, for example, to use intuitive graphical techniques to tell your code which controls are connected to specific instance variables, or outlets, and which methods, or actions, in your code are triggered by specific controls.

A nib file is not a collection of layout templates or generated code to be compiled along with your application code, as is the case with interface design tools for other development systems. It is, in fact, a set of archived objects that a Cocoa application loads, unarchives, connects, and runs. In this way, Interface Builder allows you to write code that is more completely divorced from a specific user interface, and therefore more portable and adaptable to new interfaces. You may be able to use Interface Builder, for example, to alter the user interface of a compiled application even if you don’t have access to its source code, and conversely to prototype and test a user interface without compiling an application.

I have not found an authoritative explanation of what the nib in the term nib file stands for. It is, of course, the file extension used to identify one kind of Interface Builder file, but what does it mean? Even the original NeXTstep Concepts book for version 1.0 of NeXTstep, published in 1990, refers to these files only as interface files or .nib files. Veterans of those days report that nib stands for NeXT Interface Builder.

One final note about these developer tools: Both Xcode and Interface Builder have undergone rapid change over the years, and there is no sign that the pace will slow. Apple adds new features and even radical changes in form and substance with every release of the developer tools. Even the terminology used in these tools changes over time. It is therefore very likely that passages in this book describing how to work with Xcode and Interface Builder in Mac OS X 10.6 will grow increasingly out of date as time goes by. Reading the Release Notes and other documentation for each new version of the tools is important for keeping up with these changes.

New Technologies

Objective-C, Cocoa, and Apple’s developer tools have come a long way since the beginning. The most notable new technologies, to my mind, are Cocoa Bindings and garbage collection. The transition to a 64-bit architecture, which comes to full fruition in Snow Leopard, is also important. Others might list properties, blocks, Core Data, Core Animation, or other technologies as more important.

The first two of these new technologies, Cocoa Bindings and garbage collection, are optional in most cases. You can develop an application using the old or the new technologies, at your whim, and your users almost certainly won’t notice any difference. The third technology I mentioned, the 64-bit architecture, is theoretically optional, but Apple is now giving substantial indications that it will eventually become mandatory. It requires some coding techniques, especially relating to data types, which differ from the old C-based techniques familiar to Cocoa developers.

The advantage conferred by the first two of these new technologies is strictly for your benefit. They greatly reduce the amount of code you must write, and in some ways they simplify your code. There is every reason for you to take advantage of all of these new technologies.

There is a problem, however. You as a developer need to understand the old technologies. With respect to Cocoa Bindings and another new feature, properties, the new technology still uses the old technology under the hood. In fact, there are good reasons to continue to write accessor methods in many circumstances, so you must learn how to do it. With respect to garbage collection, you may encounter edge cases or other situations where you have to write reference-counted code. This is particularly true if, for example, you write a shared framework that must be capable of working with client applications using either memory management model. Although the use of the 64-bit architecture is not really optional, you still need to be able to translate older C-based concepts and code into 64-bit compatible code.

Vermont Recipes therefore starts out using the old technologies, except that it is 64-bit capable throughout. Once you have mastered them, the book shows you how to convert the code you have written up to that point to the new technologies.

The Vermont Recipes Application Specification

The subject of the first edition of this book was a generic application implementing all of the features typically found in many applications and utilities. These included multiple documents and windows; many kinds of controls, menus, tabbed views, and drawers; and standard Macintosh techniques such as drag-and-drop editing. It was not a focused, topical application designed to serve any particular purpose, such as a music notation tool or a checkbook-balancing program. Instead, it served simply as a showcase for common user interface elements, demonstrating not only how to build them but also how they work when completed. The Vermont Recipes 1.0 application itself didn’t actually do anything useful.

I am taking a different approach in the second edition. Many of the same user interface features are coded and described—along with many newer features unheard of in the days of Jaguar—but they are repurposed to serve as user interface elements in a real application that does something useful.

The Vermont Recipes 2 application is specified, in broad strokes, as follows: It is a cookbook application for people who cook food instead of code. Its main window is designed to support a Core Data database containing all of the information needed for a large collection of recipes, although this book will not cover the implementation of the database itself. The application also allows specialized documents of two different types to be open simultaneously, one to contain recipes complete with lists of ingredients, required utensils, and cooking directions, and the other to maintain a diary recording ongoing culinary thoughts and experiences. Each kind of document can be saved separately with its own settings using a file format reserved for that type. Window objects showcasing various categories of controls and views present the contents of the database document and the diary document. The diary document, for example, provides a large, scrollable space for typing text, such as chef’s notes and tasting experiences. The application incorporates additional features, such as a Help system and support for newer Apple technologies like blocks. In addition, the application is scriptable using AppleScript. In short, if you’re planning to create a multidocument, multiwindow application, the Vermont Recipes 2 application provides a usable model for your own work.

This specification will be modified from time to time throughout the book to add new features.

Downloading and Installing the Project Files

You can download the Vermont Recipes project files from the book’s Web site (www.peachpit.com/cocoarecipes) to follow along with the book, if you prefer not to type all the code yourself. The files are annotated with references to the recipes that describe them. If you are a nonlinear thinker, you can start with the project files and look up the explanations in the book.

The downloads come for the most part in the form of compressed zip files. There is a separate file for each recipe, containing the code described up to that point in the book. After downloading one of these files, you will find it in your download folder or on your desktop under a name like Vermont Recipes 2.0.0 - Recipe 09, followed by the .zip file extension. After double-clicking it to decompress it, drag the Vermont Recipes project folder that it contains to the place where you keep your development files (for example, in your home Documents folder), open the folder, and double-click the Vermont Recipes.xcodeproj file to open it in Xcode.

You can also download the completed application and run it on your computer to see all the features that are covered in the book, and more. There are two versions of the completed application, one for Leopard and one for Snow Leopard.

  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint