Cocoa Design Patterns by Erik BuckCocoa Design Patterns by Erik Buck

Cocoa Design Patterns

byErik Buck, Donald Yacktman

Paperback | September 1, 2009

Pricing and Purchase Info

$28.99 online 
$57.99 list price
Earn 145 plum® points

Prices and offers may vary in store

Out of stock online

Not available in stores


“Next time some kid shows up at my door asking for a code review, this is the book that I am going to throw at him.”


–Aaron Hillegass, founder of Big Nerd Ranch, Inc., and author of Cocoa Programming for Mac OS X


Unlocking the Secrets of Cocoa and Its Object-Oriented Frameworks


Mac and iPhone developers are often overwhelmed by the breadth and sophistication of the Cocoa frameworks. Although Cocoa is indeed huge, once you understand the object-oriented patterns it uses, you’ll find it remarkably elegant, consistent, and simple.


Cocoa Design Patterns begins with the mother of all patterns: the Model-View-Controller (MVC) pattern, which is central to all Mac and iPhone development. Encouraged, and in some cases enforced by Apple’s tools, it’s important to have a firm grasp of MVC right from the start.


The book’s midsection is a catalog of the essential design patterns you’ll encounter in Cocoa, including

  • Fundamental patterns, such as enumerators, accessors, and two-stage creation
  • Patterns that empower, such as singleton, delegates, and the responder chain
  • Patterns that hide complexity, including bundles, class clusters, proxies and forwarding, and controllers

And that’s not all of them! Cocoa Design Patterns painstakingly isolates 28 design patterns, accompanied with real-world examples and sample code you can apply to your applications today. The book wraps up with coverage of Core Data models, AppKit views, and a chapter on Bindings and Controllers.


Cocoa Design Patterns clearly defines the problems each pattern solves with a foundation in Objective-C and the Cocoa frameworks and can be used by any Mac or iPhone developer.

Erik M. Buck founded EMB & Associates, Inc. in 1993 and built the company into a leader in the aerospace and entertainment software industries by leveraging the NeXT/Apple software technology that would later become Apple’s Cocoa frameworks. Mr. Buck has also worked in construction, taught science to 8th graders, exhibited oil on canv...
Title:Cocoa Design PatternsFormat:PaperbackDimensions:456 pages, 9 × 6.9 × 1 inPublished:September 1, 2009Publisher:Pearson EducationLanguage:English

The following ISBNs are associated with this title:

ISBN - 10:0321535022

ISBN - 13:9780321535023


Read from the Book

Preface Much of the technology embodied by Apple's Cocoa software has been in commercial use since 1988, and in spite of that maturity, Cocoa is still revolutionary. The technology has been marketed with a variety of names including NEXTSTEP, OPENSTEP, Rhapsody, and Yellow Box. It consists of a collection of reusable software frameworks that contain objects and related resources for building Mac OS X desktop and mobile applications. In recent years, Apple has expanded Cocoa dramatically and added new software developer tools to increase programmer productivity beyond the already famously high levels Cocoa already provided. Programmers are often overwhelmed by the breadth and sophistication of Cocoa when they first start using the frameworks. Cocoa encompasses a huge set of features, but it's also elegant in its consistency. That consistency results from the application of patterns throughout Cocoa's design. Understanding the patterns enables the most effective use of the frameworks and serves as a guide for writing your own applications. This book explains the object-oriented design patterns found in Apple's Cocoa frameworks. Design patterns aren't unique to Cocoa; they're recognized in many reusable software libraries and available in any software development environment. Design patterns identify recurring software problems and best practices for solving them. The primary goal of this book is to supply insight into the design and rationale of Cocoa, but with that insight, you'll be able to effectively reuse the tried and true patterns in your own software—even if you aren't using Cocoa. What Is a Design Pattern? Design patterns describe high quality practical solutions to recurring programming problems. Design patterns don't require amazing programming tricks. They're a toolbox of reusable solutions and best practices that have been refined over many years into a succinct format. They provide a vocabulary, or shorthand, that programmers can use when explaining complex software to each other. Design patterns don't describe specific algorithms or data structures like linked lists or variable length arrays, which are traditionally implemented in individual classes. The design patterns in this book don't describe specific designs for applications even though examples are provided. What the patterns do provide is a coherent map that leads you through the design of Cocoa itself. Patterns show how and why some of the best and most reusable software ever created was designed the way it was. At a minimum, design patterns contain four essential elements: The pattern name A brief description of the motivation for the pattern or the problem solved by the pattern A detailed description of the pattern and examples in Cocoa The consequences of using the pattern Parts II, III, and IV of this book contain a catalog of design patterns. Each chapter in the pattern catalog introduces a design pattern and provides the essential information you need to recognize and reuse the pattern. The pattern's name helps developers communicate efficiently. A shared vocabulary of pattern names is invaluable when explaining a system to colleagues or writing design documentation. Named patterns clarify thought, and the implications of a design—even the rationale behind a design—can be communicated with just a few words. Programmers familiar with patterns immediately infer the uses and limitations of objects composing a named pattern as well as the overall design employed and the consequences of that design. Apple's own documentation occasionally uses design pattern names in both class references and programmer's guides, but the documentation doesn't always explain what the patterns are or what they should mean to a developer. In addition, Apple frequently uses their own names for design patterns instead of the terms commonly used throughout the industry. In some cases, the differences in terminology are the result of simultaneous independent discovery. In other cases, the patterns were first recognized in Cocoa or its predecessor NEXTSTEP, and it's the industry that changed the name. The patterns described in this book are identified using both Apple's terminology and the common industry names when applicable so you can see the correlation. Each design pattern includes a description of the problem(s) and motivation for applying the pattern. Some patterns include a list of problem indicators that suggest the use of the pattern. Because Cocoa contains many patterns that are applicable in diverse situations, the patterns have been carefully organized so that the same problems in different contexts are readily identified. In some cases, related patterns that should be avoided are also identified. Finally, each pattern identifies the consequences that naturally result from its use. The consequences and trade-offs of design alternatives are crucial when evaluating which patterns to use in a particular situation. Why Focus on Design Patterns? When approaching a software technology as vast as Cocoa, it's easy to lose sight of the overall architecture and rationale of the technology. Many programmers comment that they feel lost in the multitude of classes, functions, and data structures that Cocoa provides. They can't see the forest because they're concentrating too much on individual trees. The patterns used in Cocoa provide a structure and organization that helps programmers find their way. The patterns show programmers how to reuse groups of cooperating classes even when the relationships between the classes are not fully explained in the documentation for individual classes. The goal of object-oriented programming is to maximize programmer productivity by reducing lifetime software development and maintenance costs. The principal technique used to achieve the goal is object reuse. An object that is reused saves the programmer time because the object would otherwise need to be reimplemented for each new project. Another benefit of reusing objects is that when new features are required or bugs are identified, you only need to make changes to a small number of objects, and those changes benefit other projects that rely on the same objects. Most importantly, by reusing objects, fewer total lines of code are written to solve each new problem, and that means there are fewer lines of code to maintain as well. Design patterns identify successful strategies for achieving reuse on a larger scale than individual objects. The patterns themselves and all of the objects involved in the patterns are proven and have been reused many times. The consistent use of design patterns within Cocoa contributes to the high level of productivity that Cocoa programmers enjoy. Design patterns advance the art of object-oriented programming. The patterns within Cocoa provide a guide for designing many different types of applications. Cocoa contains some of the most famously well-designed software ever produced, and following the patterns used by Cocoa will make you a better programmer even when you aren't using Cocoa. This book should satisfy your intellectual curiosity. Design patterns answer "why" as well as "what" and "how." Knowing how patterns are applied and more importantly why patterns contribute so much to productivity makes the daily job of programming more enjoyable. Guiding Principles of Design All of the design patterns described in this book have several properties in common. In each case, the goal of the pattern is to solve a problem in a general, reusable way. Several guiding principles of design help ensure that the patterns are flexible and applicable in many contexts. The same strategies that are applied to design of individual objects are applied to design patterns as well. In fact, patterns that involve many objects benefit even more from good object-oriented design than simpler systems. One reason that patterns exist is to help make sure that productivity gained from reusing the patterns exceeds the productivity gained from using individual objects—the sum is greater than the parts. Minimize Coupling As a general design goal, coupling between classes should be minimized. Coupling refers to dependencies between objects. Whenever such dependencies exist, they reduce opportunities for reusing the objects independently. Coupling also applies to subsystems within large systems of objects. It's important to look for designs that avoid coupling whenever possible. All of the Cocoa design patterns exist in part to limit or avoid coupling. For example, the overarching Model-View-Controller (MVC) pattern described in Part I of this book, "One Pattern to Rule Them All," is used throughout Cocoa to organize subsystems of classes and is applied to the design of entire applications. The primary intent of the MVC pattern is to partition a complex system of objects into three major subsystems and minimize coupling between the subsystems. Design for Change It's important to use designs that accommodate changes through the lifecycle of a software system. Designs that are too inflexible ultimately restrict opportunities for reuse. In the worst case, no reuse occurs because it's easier to redesign and reimplement a system than it is to make changes within an existing rigid design. It's possible to anticipate certain types of changes and accommodate them in a design. For example, the Cocoa Delegates pattern provides a mechanism for one object to modify and control the behavior of another object without introducing coupling between them. Cocoa provides many objects that can be controlled by optional delegates, and the key to the pattern is that the objects acting as delegates might not have even been conceived when Cocoa was designed. All of the Cocoa design patterns exist in part to accommodate change. That's just one of the reasons that Cocoa is so flexible. Emphasize Interfaces Rather Than Implementations Interfaces provide a kind of metaphorical contract between an object and the users of the object. An object's interface tells a programmer what the object is able to do but not how it will do it. In the context of reusable frameworks like Cocoa, object interfaces must remain consistent from one version of the framework to the next, or else software written to use one version of the framework may not work correctly with the next. A contract is necessary for programmers to feel confident reusing framework objects, but anyone who has tried to create a truly flexible reusable contract knows that it's a difficult task. When implementation details become part of the contract between an object and its users, it becomes difficult for framework developers to improve objects without breaking backward compatibility. Find the Optimal Granularity Many of the design patterns employed by Cocoa operate at different levels of granularity. For example, the MVC pattern is usually applied to large subsystems of cooperating classes and entire applications, but the Singleton pattern is used to make sure that only one instance of a class is ever created and provides access to that instance. The goal of patterns is to enhance software reuse. The granularity of a pattern can have a huge impact on opportunities for reuse. Certain problems are best solved by small patterns that involve only a few classes, while other problems are solved by reusing grand overarching patterns. The key is to find the optimal balance. In general, the larger patterns provide bigger productivity gains than the smaller ones, but if a pattern is too big or too general to solve a specific, narrow problem, it can't be used. For example, the MVC pattern contributes enormously to most applications, but there are some specific applications that may not benefit from its use, and in those cases the pattern provides no value. In contrast, patterns such as Anonymous Objects and Heterogeneous Containers, Enumerators, Flyweight, and Singleton are small and contribute value in every application. Cocoa provides patterns all along the spectrum. Some of the pattern descriptions address the issues of granularity and the balance that Cocoa strikes. Use Composition in Preference to Inheritance It can't be said enough times that coupling is the enemy. It is ironic that inheritance is simultaneously one of the most powerful tools in object-oriented programming and one of the leading causes of coupling. In fact, there is no tighter coupling than the relationship between a class and its inherited super-classes. Many of the patterns described in this book exist in part to reduce the need to create subclasses. The general rule is that when there is an alternative to inheritance, use the alternative. Audience This book is intended for Mac OS X programmers who are using or considering the use of Apple's Cocoa frameworks. Much of the information in this book also applies directly to the open source GNUstep project, which is available for Linux and Windows. Who Should Read This Book Objective-C, C, C++, and Java programmers should read this book. You should be familiar with the general principals of object-oriented design and object-oriented technology to understand and benefit from the design patterns presented here. Many of Cocoa's design patterns leverage features of the Objective-C language, which are not thoroughly explained in this book; however, Apple includes the document, titled The Objective-C 2.0 Programming Language, along with the free Mac OS X Developer Tools ( Some knowledge of Objective-C is required to understand the implementation of Cocoa, although experienced programmers can pick it up incrementally while reading this book. That said, this book is not a substitute for a language reference such as The Objective-C 2.0 Programming Language even though language features that contribute to Cocoa design patterns are explained as needed within the pattern descriptions. What You Need to Know This book doesn't require guru-level programming skills. The patterns used in the design of Cocoa are identified and explained in part to demystify the technology. Programmers who are new to Cocoa will benefit from the insights and wisdom embodied by Cocoa just as much as experienced veterans. However, if you are completely new to programming with C or languages derived from C, you’ll have difficulty following the in-depth analysis of how and why patterns work. You need to be comfortable with the object-oriented concepts of classes, instances, encapsulation, polymorphism, and inheritance. Without a foundation in the technology of object-oriented software development, the sometimes advanced descriptions of benefits, consequences, and trade-offs in this book could be overwhelming. This book assumes that you know C, C++, or Java and that you're familiar with object-oriented software development. As mentioned earlier, you need to know Objective-C to get the most value from this book, but Objective-C can be learned along the way. You will also need to be running a Mac OS X system with the Developer Tools installed. If you don't have the Developer Tools installed on your system, there are a couple things you can do to obtain them: If you have new Mac hardware, look in /Applications/Installers. There should be a package there (Developer.pkg), which you can double-click to install the Developer Tools. If you purchased a boxed release of Mac OS X, look for the DVD labeled Developer Tools and install them from DVD. If either of these options doesn't work for you, you can become a free online member of the Apple Developer Connection (ADC) at After you've signed up, you can download the latest set of Developer Tools from the ADC web site. (Keep in mind, though, that the download is around 300MB, so you'll need a fast connection.) This book is written based on the Leopard release of Mac OS X (version 10.5), but ultimately you will want to leverage Cocoa's design patterns when creating applications for any version of Mac OS X or for Windows and Linux with GNUstep. How This Book Is Organized This book is organized into five parts. Part I, "One Pattern To Rule Them All," describes the Model View Controller pattern that provides the overall structure and organization for Cocoa and most applications that use Cocoa. Part II, "Fundamental Patterns," identifies the patterns in Cocoa with which all other patterns are built. Part III, "Patterns That Primarily Empower by Decoupling," contains patterns that enable you to control and extend objects without introducing unnecessary coupling. Part IV, "Patterns That Primarily Hide Complexity," explains patterns that hide complexity and implementation details so programmers can confidently focus on solving problems. Part V, "Practical Tools for Pattern Application," shows practical applications of the Model View Controller design pattern with examples selected from the Cocoa frameworks. Appendix A, "Resources," provides additional references for using and understanding Cocoa and design patterns. © Copyright Pearson Education. All rights reserved.

Table of Contents

Preface     xix

Part I: One Pattern to Rule Them All     1

Chapter 1: Model View Controller     2

Chapter 2: MVC Analyzed and Applied     17

Part II : Fundamental Patterns     28

Chapter 3: Two-Stage Creation     29

Chapter 4: Template Method     43

Chapter 5: Dynamic Creation     53

Chapter 6: Category     63

Chapter 7: Anonymous Type and Heterogeneous Containers     77

Chapter 8: Enumerators     85

Chapter 9: Perform Selector and Delayed Perform     99

Chapter 10: Accessors     107

Chapter 11: Archiving and Unarchiving     123

Chapter 12: Copying     135

Part III: Patterns That Primarily Empower by Decoupling     147

Chapter 13: Singleton     148

Chapter 14: Notifications     159

Chapter 15: Delegates     175

Chapter 16: Hierarchies     191

Chapter 17: Outlets, Targets, and Actions     206

Chapter 18: Responder Chain     220

Chapter 19: Associative Storage     232

Chapter 20: Invocations     242

Chapter 21: Prototype     255

Chapter 22: Flyweight     263

Chapter 23: Decorators     268

Part IV: Patterns That Primarily Hide Complexity     274

Chapter 24: Bundles     275

Chapter 25: Class Clusters     282

Chapter 26: Façade     302

Chapter 27: Proxies and Forwarding     312

Chapter 28: Managers     328

Chapter 29: Controllers     337

Part V : Practical Tools for Pattern Application     364

Chapter 30: Core Data Models     365

Chapter 31: Application Kit Views     379

Chapter 32: Bindings and Controllers     393

Appendix: Resources     404

Index     407


Editorial Reviews

Praise for Cocoa Design Patterns   “This long-needed book is a great resource for Cocoa newcomers and veterans who want to get the why behind the what. The list of patterns gives historical perspective and answers many developer questions and the last three chapters–covering Core Data, AppKit, and Bindings–are a must-read; they reveal insights that might otherwise require hours of discussion with Apple engineers or access to source code.” –Tim Burks, Software Developer and Creator of the Nu Programming Language,   “This book is a comprehensive and authoritative treatment of design patterns and their practical applications in Cocoa projects. I recommend this book to anyone who wants to advance from intermediate to expert proficiency as a Macintosh developer.” –John C. Randolph, Vice President Engineering, Stealth Imaging, Inc.   “Cocoa Design Patterns is a fantastic book that will show you the ins and outs of software design patterns, how Cocoa makes use of them, and how to apply them to your own applications for better, more robust, and more maintainable software.” –August Trometer, Owner of FoggyNoggin Software   “Cocoa Design Patterns is superb! It is highly readable, thoroughly enjoyable, and filled to the brim with wisdom that will make you a more efficient and effective programmer. The authors utilize a consistent and self-contained approach to each chapter, making it easy to return to use as a reference. However, the material is so interesting and vital to Cocoa programmers that you’ll want to read it from cover to cover.” –David Mandell, Independent Developer   “Erik and Donald’s book really helped me out with the conceptual side of programming. It caused me to realize where I was going wrong in my code and helped me sort out my design issues.” –Eoin Houlihan   “This book is recommended for any programmer interested in a deeper understanding of Cocoa. Reading it might have helped me become a better software engineer in any object-oriented language. I’ll keep it handy as a constant reference and look forward to reading it again more carefully.” –Daryl Spitzer