Nutting Cocoa on the Mac Learn Companion eBook Available Trim: 7.5 x 9.25 spine = 0.875" 392 page count Mastering Mac OS X’s Cocoa Frameworks, with Xcode and Objective-C Jack Nutting | David Mark | Jeff LaMarche Learn Cocoa on the Mac COMPANION eBOOK SEE LAST PAGE FOR DETAILS ON $10 eBOOK VERSION US $39.99 Shelve in Mac User level: Beginner-Intermediate www.apress.com SOURCE CODE ONLINE BOOKS FOR PROFESSIONALS BY PROFESSIONALS ® ISBN 978-1-4302-1859-3 9 781430 218593 5 39 9 9 this print for content only—size & color not accurate CYAN MAGENTA YELLOW BLACK PANTONE 123 C SPOT MATTE L earn Cocoa on the Mac presents complete coverage of the latest Cocoa frameworks in a logical, step-by-step progression of discussions and tutori- als. The base frameworks are introduced and demonstrated: AppKit for all the standard graphical controls and the Foundation framework classes for Objec- tive-C. You’ll dig into the basic UI objects and then attack the fundamentals of Cocoa Bindings, part of Apple’s comprehensive implementation of the Model- View-Controller (MVC) design pattern. Then it’s on to a comprehensive look at Core Data, the key to all data-driv- en applications, from basic concepts to data modeling and even more ad- vanced data techniques. You’ll also learn drawing with Core Graphics and Core Animation, le management, as well as the latest technique introduced with Snow Leopard: using Grand Central Dispatch to make your applications concurrent, in order to make the most of today’s multi-core processors. Through a combination of pragmatic problem-solving and a deep respect for Cocoa’s underlying design philosophies, you’ll learn about the diverse capabilities of the various APIs and then how to put them all to use in dy- namic combinations. And when you’re done, you’ll have an integrated view of Cocoa’s components and how to use them to build great Mac OS X apps with this rich and mature toolset. What you’ll learn • How to build your own Cocoa applications—this is much more than just a quick introduction to Cocoa! • What makes Cocoa and its MVC architecture tick • Ecient coding techniques for stitching together powerful APIs • How to leverage Cocoa’s design patterns and put them to proper use in your own code Who is this book for? Those new to Mac OS X development with a basic understanding of object- oriented programming and seasoned developers who want to master the lat- est Cocoa frameworks, as well as iPhone developers who want to extend their knowledge of Cocoa Touch to include Mac-specic technologies. Jack Nutting, veteran Cocoa expert back to the early days of NextStep, along with Dave Mark and Je LaMarche, the bestselling authors of Beginning iPhone 3 Development, share their knowledge of and keen insights for making great Mac OS X apps. RELATED TITLES www.it-ebooks.info www.it-ebooks.info i Learn Cocoa on the Mac ■ ■ ■ Jack Nutting, Dave Mark and Jeff LaMarche www.it-ebooks.info ii Learn Cocoa on the Mac Copyright © 2010 by Jack Nutting, David Mark and Jeff LaMarche All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN-13 (pbk): 978-1-4302-1859-3 ISBN-13 (electronic): 978-1-4302-1860-9 Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1 Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. President and Publisher: Paul Manning Lead Editors: Clay Andres, Brian MacDonald, Matthew Moodie, Douglas Pundick Technical Reviewer: Mark Dalrymple Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh Coordinating Editor: Mary Tobin Copy Editor: Tracy Brown Collins Compositor: MacPS, LLC Indexer: John Collin Artist: April Milne Cover Designer: Anna Ishchenko Photo Credit: Weronica Meijer Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders- ny@springer-sbm.com, or visit http://www.springeronline.com. For information on translations, please e-mail info@apress.com, or visit http://www.apress.com. Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at http://www.apress.com/info/bulksales. The information in this book is distributed on an “as is” basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. www.it-ebooks.info iii www.it-ebooks.info iv Contents at a Glance ■Contents at a Glance iv ■Contents v ■Foreword xi ■About the Authors xii ■About the Technical Reviewer xiii ■Acknowledgments xiv ■Preface xv ■Chapter 1: Must Love Cocoa 1 ■Chapter 2: Hello, World 5 ■Chapter 3: Lights, Camera… Actions! (and Outlets, Too) 29 ■Chapter 4: GUI Components 55 ■Chapter 5: Using Table Views 91 ■Chapter 6: Cocoa Bindings 105 ■Chapter 7: Core Data Basics 133 ■Chapter 8: Core Data Relationships 165 ■Chapter 9: Search and Retrieve Core Data with Criteria 183 ■Chapter 10: Windows and Menus and Sheets 197 ■Chapter 11: Document-Based Applications 221 ■Chapter 12: Exceptions, Signals, Errors, and Debugging 239 ■Chapter 13: Drawing in Cocoa 259 ■Chapter 14: Advanced Drawing Topics 279 ■Chapter 15: Working with Files 303 ■Chapter 16: Concurrency 315 ■Chapter 17: Future Paths 335 ■Index 347 www.it-ebooks.info v Contents ■Contents at a Glance iv ■Contents v ■Foreword xi ■About the Authors xii ■About the Technical Reviewer xiii ■Acknowledgments xiv ■Preface xv ■Chapter 1: Must Love Cocoa 1 Get a Mac and Download the Tools 2 Download the Source Code 3 Getting Help 3 What You Need to Know Before You Begin 3 Are You Ready? 4 ■Chapter 2: Hello, World 5 Building “Hello, World” 5 Exploring the Nib File 9 The Library 10 Dragging Out a Label 12 Using the Blue Guidelines 13 The Inspector Window 14 The Attributes Inspector 15 Change the Label’s Color and Font 17 Using the Menu Editor 19 Creating Your Application Icon 21 Adding Your Icon to Your Project 22 Property Lists 25 Running Your Application 25 www.it-ebooks.info ■ CONTENTS vi Sharing Your Creation With the World 26 Goodbye, Hello World 28 ■Chapter 3: Lights, Camera… Actions! (and Outlets, Too) 29 This Chapter’s Application 30 Frameworks, Frameworks Everywhere 30 The Foundation Framework 31 The AppKit Framework 31 The Cocoa Way: Model-View-Controller 32 Outlets, Actions, and Controllers 33 Declaring Outlets 33 Declaring Actions 34 Outlets and Actions in Action 35 Enabling Garbage Collection 35 Creating Our Controller Class 37 Declaring an Action and Outlet 38 Back to Interface Builder 39 Setting Up the Window 42 Designing the Window’s Interface 46 Connecting the Outlet 48 Connecting the Buttons to Our Action 49 Implementing the Action Method 50 The Application Delegate 51 Configuring the Application to Quit on Window Close 52 Using the Documentation Browser 53 Bring It on Home 54 ■Chapter 4: GUI Components 55 Creating the VillainTracker Application 57 Creating the VillainTrackerAppDelegate Class 58 Planning for the GUI 60 Building Your Interface 62 Bringing Out Your Text Fields 62 Letting them Pick Dates 64 Creating the Combo Box 65 Indicating a Rating with a Level Indicator 66 Adding Radio Buttons in a Matrix 67 Adding an Image View 70 Adding Checkboxes in a Matrix 71 Configuring a Popup Button 72 Inserting a Text View 73 Making Logical Groupings 73 Resizing 76 Time for the Controller 78 Making All the Connections 78 Getting Started with Coding 80 Standardizing Key Names 80 Creating the Default Villain 81 Paying Attention to Detail 82 www.it-ebooks.info ■ CONTENTS vii Responding to Input 87 In Conclusion 90 ■Chapter 5: Using Table Views 91 Preparing AppController for Multiple Villains 91 Making Way for the Table View 93 Tweaking the Autosizing Characteristics 96 Making Some New Connections 98 Making Way for the Table View: Code Edition 99 The Table View Needs Your Help 100 Adding and Deleting Villains 102 In Conclusion 104 ■Chapter 6: Cocoa Bindings 105 Binding to Simple Controls 106 Create the DungeonThing Project 106 Create a Preferences Window 107 Binding to NSUserDefaultsController 111 Create the Main Window 114 Set Up the DungeonThingAppDelegate 116 Define Your Constants 116 Specify Default Preferences Values 117 Create the Action Methods 118 Binding to a Table View 120 Make the Code Bindings-Ready 121 Show History in Tables 124 Create and Configure an Array Controller 126 Bind Table Display via the Array Controller 128 Bind a Text Field via the Array Controller’s Selection 128 Making Sure it Works 129 Rinse, Repeat, Rinse, Repeat 129 Okay, But How Did That Work? 129 Key-Value Coding 129 Key-Value Observing 131 Cocoa Bindings: How It Works 131 In Conclusion 132 ■Chapter 7: Core Data Basics 133 What You’ve Been Missing 133 Creating MythBase 135 Defining the Model 136 The Automatic GUI 142 Refining the GUI 145 Exploring the Template Code 150 The App Delegate Interface 150 The App Delegate Implementation 152 Adding Business Logic 159 Validating Single Attributes 160 Validating Multiple Attributes 160 Creating a Custom Attribute 163 www.it-ebooks.info ■ CONTENTS viii In Conclusion 164 ■Chapter 8: Core Data Relationships 165 Modeling New Entities and Relationships 166 Model Versioning and Migrations 167 Preparing for Multiple Model Versions 167 Adding New Entities 167 Add Relationships 168 Creating a Simple Migration 170 Time to Run 172 Updating the GUI 173 Create the Band Window 173 Giving Useful Names to Array Controllers 174 Putting People in Bands 175 Showing the Bands’ Members 177 Create a Venue Window 179 Adding a Gig List to the Band Window 179 Wrapping Up Relationships 181 ■Chapter 9: Search and Retrieve Core Data with Criteria 183 Creating QuoteMonger 183 Create the Project and Its Data Model 184 The Data Entry Window 185 Creating the Quote Finder Window 188 Limiting Results with NSPredicate 189 Creating Predicates 189 Specifying an NSAppController’s Predicate in Interface Builder 191 User-Defined Predicates 191 Adding a Predicate to the App Delegate 192 Add a Predicate Editor to the Search Window 193 Configuring the Predicate Editor 193 Saving a Predicate 195 In Conclusion 196 ■Chapter 10: Windows and Menus and Sheets 197 NSWindow and NSPanel 197 Standard System Panels 201 A Controller With a Nib of Its Own 205 Modal Windows 209 System Menus 211 Standard Application Menu Items 212 Your Own Menus 212 Sheets 218 Wrap-up 220 ■Chapter 11: Document-Based Applications 221 Creating the ColorMix Application 222 Examining the Default Nib Files 223 Defining the Model 223 Setting Two Colors 224 The Simplest of GUIs 225 www.it-ebooks.info [...]... implemented as a Cocoa class Another benefit of using Cocoa is that it is tightly integrated with Mac OS X Build your application using Cocoa, and your application will play well with others and will interface seamlessly with Mac OS X elements like the Finder and the Dock WHEN IS 20 YEARS NOT 20 YEARS? Cocoa has been around in one form or another since 1986 The technologies that we call Cocoa evolved... 1990s, and then later as an independent consultant Dave Mark is a long-time Mac developer and author and has written a number of books on Macintosh development, including Learn C on the Macintosh, The Macintosh Programming Primer series, and Ultimate Mac Programming His blog can be found at http://www.davemark.com xii www.it-ebooks.info About the Technical Reviewer Mark Dalrymple is a long-time Mac and. .. the Mac OS, what we now know as Mac OS X, basing much of the new operating system on technologies acquired from NeXT As Mac OS X evolved, so did Cocoa Apple added technologies from the classic Mac OS, like QuickTime, as well as completely new technologies, like the Quartz rendering system that enables all the fancy visual 1 www.it-ebooks.info 2 CHAPTER 1: Must Love Cocoa effects and animation that OS. .. sure that they kept the Mac s famed ease-of-use in the process Bottom line: Cocoa is constantly evolving and expanding The development tools, libraries, and frameworks you’ll be learning in this book are the result of more than 20 years of experimentation and refinement Get a Mac and Download the Tools Before you can begin creating applications with Cocoa, you’ll need a Macintosh computer It doesn’t... and Dorotea, who’ve put up with my many long nights and “lost weekends” as I worked on this book, and have been more patient than I could have hoped for; this book is dedicated to them xiv www.it-ebooks.info Preface I first encountered Cocoa as a college student in about 1989 Of course, that was before the iPhone, before Mac OS X, and before it was even called Cocoa Back then, the seed of today’s Cocoa. .. loops, variables, pointers, and linked lists This book also assumes that you understand the fundamentals of object-oriented programming and are familiar with the Objective-C programming language Starting with Mac OS X Leopard 10.5, a new version of the language was introduced, called Objective-C 2.0 Don’t worry if you’re not familiar with the more recent additions to the Objective-C language We’ll be... crossplatform toolkits, Internet publishing tools, high-performance web servers, and end-user desktop applications He is also the principal author of Advanced Mac OS X Programming (Big Nerd Ranch, 2005) and Learn Objective-C on the Mac (Apress, 2009) In his spare time, Mark plays trombone and bassoon, and makes balloon animals xiii www.it-ebooks.info Acknowledgments This book would never have been possible... for Mac OS X applications As you make your way through this book, you’ll learn all about the Cocoa frameworks and runtime environment For the moment, think of Cocoa as a programmer’s assistant that takes care of much of the housekeeping that goes along with Mac development Almost every common task performed by a Mac application, from drawing a window to blinking the cursor in a text field, is handled... details with a fine-toothed comb, keeping me honest and making me look good at the same time Brian MacDonald’s vantage point as someone with great technical knowledge, but not detailed experience with Cocoa, helped uncover bits and pieces of the book that needed to be expanded or compacted Throughout the last several months of the writing, Mary Tobin has been consistently patient and helpful with this... The Mac is a great computing platform, and Cocoa is the best tool to use to build your Mac applications If you are coming to the Mac from another platform, you may find it a bit disorienting working with Cocoa and Objective-C Even though you might find it hard to get your bearings at first, as you make your way through this book, we’re confident that you’ll soon start to wrap your head around the “Cocoa . Nutting Cocoa on the Mac Learn Companion eBook Available Trim: 7.5 x 9.25 spine = 0.875" 392 page count Mastering Mac OS X’s Cocoa Frameworks, with Xcode and Objective-C Jack Nutting. implemented as a Cocoa class. Another benefit of using Cocoa is that it is tightly integrated with Mac OS X. Build your application using Cocoa, and your application will play well with others and will. is this book for? Those new to Mac OS X development with a basic understanding of object- oriented programming and seasoned developers who want to master the lat- est Cocoa frameworks, as well