Home > Store

Cocoa Programming for Mac OS X, 4th Edition

Register your product to gain access to bonus material or receive a coupon.

Cocoa Programming for Mac OS X, 4th Edition

eBook (Watermarked)

  • Your Price: $31.99
  • List Price: $39.99
  • Includes EPUB and PDF
  • About eBook Formats
  • This eBook includes the following formats, accessible from your Account page after purchase:

    ePub EPUB The open industry format known for its reflowable content and usability on supported mobile devices.

    Adobe Reader PDF The popular standard, used most often with the free Adobe® Reader® software.

    This eBook requires no passwords or activation to read. We customize your eBook by discreetly watermarking it with your name, making it uniquely yours.


  • Copyright 2012
  • Dimensions: 7" x 9-1/8"
  • Edition: 4th
  • eBook (Watermarked)
  • ISBN-10: 0-13-290221-4
  • ISBN-13: 978-0-13-290221-2

The best-selling introduction to Cocoa, once again updated to cover the latest Mac programming technologies, and still enthusiastically recommended by experienced Mac OS X developers. 

“Cocoa® Programming for Mac® OS X is considered by most to be the de-facto intro-to-OS X programming text.”

—Bob Rudis, the Apple Blog

“I would highly recommend this title to anyone interested in Mac development. Even if you own the previous edition, I think you’ll find the new and revised content well worth the price.”

—Bob McCune, bobmccune.com 

If you’re developing applications for Mac OS X, Cocoa® Programming for Mac® OS X, Fourth Edition, is the book you’ve been waiting to get your hands on. If you’re new to the Mac environment, it’s probably the book you’ve been told to read first.

Covering the bulk of what you need to know to develop full-featured applications for OS X, written in an engaging tutorial style, and thoroughly class-tested to assure clarity and accuracy, it is an invaluable resource for any Mac programmer. Specifically, Aaron Hillegass and Adam Preble introduce the two most commonly used Mac developer tools: Xcode and Instruments. They also cover the Objective-C language and the major design patterns of Cocoa. Aaron and Adam illustrate their explanations with exemplary code, written in the idioms of the Cocoa community, to show you how Mac programs should be written. After reading this book, you will know enough to understand and utilize Apple’s online documentation for your own unique needs. And you will know enough to write your own stylish code.

Updated for Mac OS X 10.6 and 10.7, this fourth edition includes coverage of Xcode 4, blocks, view-based table views, Apple’s new approach to memory management (Automatic Reference Counting), and the Mac App Store. This edition adds a new chapter on concurrency and expands coverage of Core Animation. The book now devotes a full chapter to the basics of iOS development.

Sample Content

Table of Contents

Preface xix

Acknowledgments xxi


Chapter 1: Cocoa: What Is It? 1

A Little History 1

Tools 3

Language 4

Objects, Classes, Methods, and Messages 5

Frameworks 6

How to Read This Book 7

Typographical Conventions 7

Common Mistakes 8

How to Learn 8

Chapter 2: Let’s Get Started 11

In Xcode 11

In Interface Builder 15

A Look at Objective-C 25

Documentation 31

What Have You Done? 31

Chronology of an Application 32

Chapter 3: Objective-C 35

Creating and Using Instances 35

Using Existing Classes 37

Creating Your Own Classes 48

The Debugger 58

What Have You Done? 63

Meet the Static Analyzer 63

For the More Curious: How Does Messaging Work? 65

Challenge 66

Chapter 4: Memory Management 67

Living with Manual Reference Counting 69

Accessor Methods 77

Living with ARC 80

Chapter 5: Target/Action 83

Some Commonly Used Subclasses of NSControl 85

Start the SpeakLine Example 89

Lay Out the XIB File 90

Implementing the SpeakLineAppDelegate Class 94

For the More Curious: Setting the Target Programmatically 96

Challenge 96

Debugging Hints 98

Chapter 6: Helper Objects 99

Delegates 100

The NSTableView and Its dataSource 104

Lay Out the User Interface 107

Make Connections 109

Edit SpeakLineAppDelegate.m 110

For the More Curious: How Delegates Work 113

Challenge: Make a Delegate 114

Challenge: Make a Data Source 114

Chapter 7: Key-Value Coding and Key-Value Observing 117

Key-Value Coding 117

Bindings 119

Key-Value Observing 120

Making Keys Observable 121

Properties 124

For the More Curious: Key Paths 126

For the More Curious: Key-Value Observing 127

Chapter 8: NSArrayController 129

Starting the RaiseMan Application 130

Key-Value Coding and nil 139

Add Sorting 140

For the More Curious: Sorting without NSArrayController 141

Challenge 1 142

Challenge 2 142

Chapter 9: NSUndoManager 145

NSInvocation 145

How the NSUndoManager Works 146

Adding Undo to RaiseMan 148

Key-Value Observing 152

Undo for Edits 153

Begin Editing on Insert 156

For the More Curious: Windows and the Undo Manager 158

Chapter 10: Archiving 159

NSCoder and NSCoding 160

The Document Architecture 163

Saving and NSKeyedArchiver 167

Loading and NSKeyedUnarchiver 168

Setting the Extension and Icon for the File Type 170

For the More Curious: Preventing Infinite Loops 172

For the More Curious: Creating a Protocol 173

For the More Curious: Automatic Document Saving 174

For the More Curious: Document-Based Applications without Undo 175

Universal Type Identifiers 175

Chapter 11: Basic Core Data 177

NSManagedObjectModel 177

Interface 179

For the More Curious: View-Based versus Cell-Based Table Views 191

Challenge 191

Chapter 12: NIB Files and NSWindowController 193

NSPanel 193

Adding a Panel to the Application 194

For the More Curious: NSBundle 204

Challenge 206

Chapter 13: User Defaults 207

NSDictionary and NSMutableDictionary 208

NSUserDefaults 210

Setting Defaults 212

Letting the User Edit the Defaults 213

Using the Defaults 215

For the More Curious: NSUserDefaultsController 217

For the More Curious: Reading and Writing Defaults from the Command Line 217

Challenge 219

Chapter 14: Using Notifications 221

What Notifications Are and Are Not 221

What Notifications Are Not 222

NSNotification 222

NSNotificationCenter 222

Posting a Notification 224

Registering as an Observer 225

Handling the Notification When It Arrives 226

The userInfo Dictionary 226

For the More Curious: Delegates and Notifications 227

Challenge 228

Chapter 15: Using Alert Panels 229

Make the User Confirm the Deletion 230

Challenge 232

Chapter 16: Localization 233

Localizing a NIB File 234

String Tables 236

For the More Curious: ibtool 239

For the More Curious: Explicit Ordering of Tokens in Format Strings 240

Chapter 17: Custom Views 241

The View Hierarchy 241

Get a View to Draw Itself 243

Drawing with NSBezierPath 248

NSScrollView 250

Creating Views Programmatically 252

For the More Curious: Cells 253

For the More Curious: isFlipped 255

Challenge 255

Chapter 18: Images and Mouse Events 257

NSResponder 257

NSEvent 257

Getting Mouse Events 259

Using NSOpenPanel 259

Composite an Image onto Your View 264

The View’s Coordinate System 266

Autoscrolling 268

For the More Curious: NSImage 269

Challenge 270

Chapter 19: Keyboard Events 271

NSResponder 273

NSEvent 273

Create a New Project with a Custom View 274

For the More Curious: Rollovers 282

The Fuzzy Blue Box 284

Chapter 20: Drawing Text with Attributes 285

NSFont 285

NSAttributedString 286

Drawing Strings and Attributed Strings 289

Making Letters Appear 289

Getting Your View to Generate PDF Data 291

For the More Curious: NSFontManager 293

Challenge 1 293

Challenge 2 294

Chapter 21: Pasteboards and Nil-Targeted Actions 295

NSPasteboard 296

Add Cut, Copy, and Paste to BigLetterView 298

Nil-Targeted Actions 300

For the More Curious: Which Object Sends the Action Message? 303

For the More Curious: UTIs and the Pasteboard 303

For the More Curious: Lazy Copying 304

Challenge 1 305

Challenge 2 305

Chapter 22: Categories 307

Add a Method to NSString 307

For the More Curious: Declaring Private Methods 309

Chapter 23: Drag-and-Drop 311

Make BigLetterView a Drag Source 312

Make BigLetterView a Drag Destination 315

For the More Curious: Operation Mask 319

Chapter 24: NSTimer 321

Lay Out the Interface 323

Make Connections 325

Add Code to TutorController 326

For the More Curious: NSRunLoop 328

Challenge 328

Chapter 25: Sheets 329

Adding a Sheet 330

For the More Curious: contextInfo 335

For the More Curious: Modal Windows 336

Chapter 26: Creating NSFormatters 339

A Basic Formatter 341

The Delegate of the NSControl Class 347

Checking Partial Strings 348

Formatters That Return Attributed Strings 350

For the More Curious: NSValueTransformer 351

Chapter 27: Printing 353

Dealing with Pagination 353

For the More Curious: Are You Drawing to the Screen? 358

Challenge 358

Chapter 28: Web Services 359

RanchForecast Project 360

Opening URLs 368

Challenge: Add a WebView 369

Chapter 29: Blocks 371

Block Syntax 373

Challenge: Design a Delegate 381

Chapter 30: Developing for iOS 383

Porting RanchForecast to iOS 383

RootViewController 386

Add a Navigation Controller 388

ScheduleViewController 391

UITableViewController 392

Pushing View Controllers 393

Challenge 395

Chapter 31: View Swapping 397

Get Started 398

Add View Swapping to MyDocument 401

Resizing the Window 403

Chapter 32: Core Data Relationships 407

Edit the Model 407

Create Custom NSManagedObject Classes 409

Lay Out the Interface 411

EmployeeView.xib 413

Events and nextResponder 414

Chapter 33: Core Animation 417

Scattered 417

Implicit Animation and Actions 423

Challenge 1 425

Challenge 2 425

Chapter 34: Concurrency 427

Multithreading 427

Improving Scattered: Time Profiling in Instruments 431

NSOperationQueue 435

For the More Curious: Faster Scattered 438

Challenge 439

Chapter 35: Cocoa and OpenGL 441

A Simple Cocoa/OpenGL Application 442

Chapter 36: NSTask 451

ZIPspector 451

Challenge: .tar and .tgz files 460

Chapter 37: Distributing Your App 461

Build Configurations 461

Creating a Release Build 464

Application Sandboxing 466

The Mac App Store 468

Chapter 38: The End 471


Index 473


Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020