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 [...]... code archive on the Apress Learn Cocoa on the Mac web page: http://www.apress.com/book/view/1430218592 You’ll find the source code archive in the Book Resources area on the left side of the page Click the link, download the zip archive, and move the Learn Cocoa Projects folder to a location in your Documents folder You’ll also find a link on the Apress Learn Cocoa on the Mac web page, in the Book Resources... Hello, World (the size of its font in particular) determine the vertical size of the label You don’t change the height of the label by resizing it You only use the resize handles to change the width of the label Let’s center the label Make sure the left side of the label is lined up with the blue guideline near the left edge of the window Then, grab the right resize handle and drag out the label until... install If you don’t have a high-speed internet connection, you may find the developer tools on one of the CDs or DVDs that came with your Mac That said, if possible, you should try to find a way to download the latest version NOTE: If you’ve already installed the iPhone SDK, then you’re all set When you install the iPhone SDK on your computer, it also installs all the tools needed for creating Cocoa programs... Single-click the disclosure triangle next to the word Library in the organization pane (the top part of the library window), which should reveal a number of additional categories The first one below Library should be called Cocoa, and it should also have a disclosure triangle next to it also Click that one as well There are three sub-items under Cocoa The first one is called Application, and contains objects... uses these blue guidelines to indicate that the item you are dragging is aligned properly with the items around it In this case, the guideline is telling you that your label is the proper distance from the left edge of the window NOTE: One of the things that have made using the Mac such a pleasant experience over the years has been the consistency of the user interface In the vast majority of Mac applications,... 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 from the NeXTStep... located in the folder /Developer/Applications Just in case you’ve never used Xcode before, we’re going to walk you through the process of creating a new project Start by selecting New Project… from the File menu, or by typing N When the New Project Assistant comes up (see Figure 2–1), select Application from under the Mac OS X heading in the left column, then select the Cocoa Application icon from the upper-right... faster machine, but for now just about any Mac made this millennium will work fine for learning what you need to learn Any Intelbased Mac, and almost all PowerPC Macs with a G4 or G5 processor will run Mac OS X 10.5 (Leopard) If you want to run the newer Mac OS X 10.6 (Snow Leopard), the PowerPC machines won’t do; you’ll need to have an Intel machine You’ll also need to join Apple Developer Connection... AppKit, the application building tools developed for the NeXT platform When Apple bought NeXT in 1996, they began building a new version of 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. .. all the fancy visual 1 www.it-ebooks.info 2 CHAPTER 1: Must Love Cocoa effects and animation that OS X uses They also made 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 . 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. 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