Cocoa Programming For OS X: The Big Nerd Ranch Guide - Pearsoncmg

Transcription

Cocoa Programming for OS X: The Big Nerd Ranch Guideby Aaron Hillegass, Adam Preble and Nate ChandlerCopyright 2015 Big Nerd Ranch, LLC.All rights reserved. Printed in the United States of America. This publication is protected by copyright, andpermission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system,or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. Forinformation regarding permissions, contactBig Nerd Ranch, LLC.200 Arizona Ave NEAtlanta, GA 30307(770) bignerdranch.comThe 10-gallon hat with propeller logo is a trademark of Big Nerd Ranch, LLC.Exclusive worldwide distribution of the English edition of this book byPearson Technology Group800 East 96th StreetIndianapolis, IN 46240 USAhttp://www.informit.comThe authors and publisher have taken care in writing and printing this book but make no expressed or impliedwarranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidentalor consequential damages in connection with or arising out of the use of the information or programs containedherein.Many of the designations used by manufacturers and sellers to distinguish their products are claimed astrademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, thedesignations have been printed with initial capital letters or in all capitals.ISBN-10 0134077113ISBN-13 978-0134077116Fifth edition, first printing, April 2015Release D.5.1.1

For Aaron’s sons, Walden and Otto For Adam’s daughters, Aimee and Leah For Nate’s nieces and nephewsiii

This page intentionally left blank

AcknowledgmentsCreating this book required the efforts of many people. We want to thank them for their help. Theircontributions have made this a better book than we could have ever written alone.Thanks to the students who took the Cocoa programming course at the Big Nerd Ranch. They helpedus work the kinks out of the exercises and explanations that appear here. Their curiosity inspired us tomake the book more comprehensive, and their patience made it possible.Thank you to all the readers of the first four editions who made such great suggestions on our forums( http://forums.bignerdranch.com/ ).Thank you to our technical reviewers, Juan Pablo Claude, Chris Morris, Nick Teissler, Pouria Almassi,and John Gallagher, who made great additions and caught many of our most egregious errors.Finally, a very big thank you to our support team in writing this book: Liz Holaday, for copy-editing;Chris Loper, whose excellent tool chain made writing this book that much easier; and most of all SusanLoper, whose collaboration helped us write the kind of book we believe this technology deserves.v

This page intentionally left blank

Table of ContentsIntroduction . xviiAbout This Book . xviiPrerequisites . xviiiTypographical conventions . xviiiWhat’s new in the fifth edition? . xviiiThe Story of Cocoa . xviiiNeXTSTEP and OpenStep . xixFrom NeXTSTEP to OS X to iOS . xixOSX, Unix, and Cocoa . xxIntroducing the Swift Language . xxThe Cocoa Frameworks . xxiTools for Cocoa Programming . xxiSome Advice on Learning . xxii1. Let’s Get Started . 1Creating an Xcode Project . 1Getting around in Xcode . 3Application Design . 4Model-View-Controller . 4Creating the MainWindowController class . 6Creating the User Interface in Interface Builder . 8Adding view objects . 9Configuring view objects . 11XIB files and NIB files . 14Showing the Window . 14Making Connections . 17Creating an outlet . 17Connecting an outlet . 18Defining an action method . 19Connecting actions . 20Creating the Model Layer . 22Connecting the Model Layer to the Controller . 24Improving Controller Design . 242. Swift Types . 27Introducing Swift . 27Types in Swift . 27Using Standard Types . 28Inferring types . 30Specifying types . 30Literals and subscripting . 32Initializers . 33Properties . 34Instance methods . 34Optionals . 34Subscripting dictionaries . 36Loops and String Interpolation . 36vii

Cocoa Programming for OS XEnumerations and the Switch Statement .Enumerations and raw values .Exploring Apple’s Swift Documentation .3. Structures and Classes .Structures .Instance methods .Operator Overloading .Classes .Designated and convenience initializers .Add an instance method .Inheritance .Computed Properties .Reference and Value Types .Implications of reference and value types .Choosing between reference and value types .Making Types Printable .Swift and Objective-C .Working with Foundation Types .Basic bridging .Bridging with collections .Runtime Errors .More Exploring of Apple’s Swift Documentation .Challenge: Safe Landing .Challenge: Vector Angle .4. Memory Management .Automatic Reference Counting .Objects have reference counts .Deallocating objects in a hierarchy .Strong and Weak References .Strong reference cycles .Unowned references .What is ARC? .5. Controls .Setting up RGBWell .Creating the MainWindowController class .Creating an empty XIB file .Creating an instance of MainWindowController .Connecting a window controller and its window .About Controls .Working with Controls .A word about NSCell .Connecting the slider’s target and action .A continuous control .Setting the slider’s range values .Adding two more sliders .NSColorWell and NSColor .Disabling a control .Using the Documentation 8

Cocoa Programming for OS XChanging the color of the color well . 91Controls and Outlets . 93Implicitly unwrapped optionals . 95For the More Curious: More on NSColor . 95For the More Curious: Setting the Target Programmatically . 96Challenge: Busy Board . 96Debugging Hints . 976. Delegation . 99Setting up SpeakLine . 99Creating and using an Xcode snippet . 101Creating the user interface . 103Synthesizing Speech . 106Updating Buttons . 107Delegation . 109Being a delegate . 110Implementing another delegate . 112Common errors in implementing a delegate . 114Cocoa classes that have delegates . 115Delegate protocols and notifications . 115NSApplication and NSApplicationDelegate . 115The main event loop . 116For the More Curious: How Optional Delegate Methods Work . 116Challenge: Enforcing a Window’s Aspect Ratio . 1177. Working with Table Views . 119About Table Views . 119Delegates and data sources . 120The table view-data source conversation . 120SpeakLine’s table view and helper objects . 121Getting Voice Data . 121Retrieving friendly names . 122Adding a Table View . 123Table view and related objects . 124Tables, Cells, and Views . 126Table cell views . 127The NSTableViewDataSource Protocol . 128Conforming to the protocol . 128Connecting the dataSource outlet . 128Implementing data source methods . 129Binding the text field to the table cell view . 130The NSTableViewDelegate Protocol . 131Making a connection with the assistant editor . 132Implementing a delegate method . 133Pre-selecting the default voice . 133Challenge: Make a Data Source . 1348. KVC, KVO, and Bindings . 135Bindings . 136Setting up Thermostat . 136Using bindings . 137ix

Cocoa Programming for OS XKey-value observing . 139Making keys observable . 140Binding other attributes . 142KVC and Property Accessors . 145KVC and nil . 146Debugging Bindings . 146Using the Debugger . 147Using breakpoints . 148Stepping through code . 149The LLDB console . 151Using the debugger to see bindings in action . 152For the More Curious: Key Paths . 153For the More Curious: More on Key-Value Observing . 154For the More Curious: Dependent Keys . 155Challenge: Convert RGBWell to Use Bindings . 1569. NSArrayController . 157RaiseMan’s Model Layer . 158RaiseMan’s View Layer . 160Introducing NSArrayController . 160Adding an Array Controller to the XIB . 162Binding the Array Controller to the Model . 163Binding the Table View’s Content to the Array Controller . 164Connecting the Add Employee Button . 164Binding the Text Fields to the Table Cell Views . 165Formatting the Raise Text Field . 167Connecting the Remove Button . 169Binding the Table View’s Selection to the Array Controller . 169Configuring RaiseMan’s Remove Button . 171Sorting in RaiseMan . 171How Sorting Works in RaiseMan . 174For the More Curious: The caseInsensitiveCompare( :) Method . 175For the More Curious: Sorting Without NSArrayController . 176For the More Curious: Filtering . 177For the More Curious: Using Interface Builder’s View Hierarchy Popover . 178Challenge: Sorting Names by Length . 18010. Formatters and Validation . 181Formatters . 181Formatters, programmatically . 181Formatters and a control’s objectValue . 182Formatters and localization . 183Validation with Key-Value Coding . 183Adding Key-Value validation to RaiseMan . 183For the More Curious: NSValueTransformer . 18711. NSUndoManager . 189Message Passing and NSInvocation . 189How the NSUndoManager Works . 190Using NSUndoManager . 191Key-Value Coding and To-Many Relationships . 192x

Cocoa Programming for OS XAdding Undo to RaiseMan . 194Key-Value Observing . 195Using the Context Pointer Defensively . 196Undo for Edits . 197Begin Editing on Insert . 199For the More Curious: Windows and the Undo Manager . 20112. Archiving . 203NSCoder and NSCoding . 204Encoding . 204Decoding . 205The Document Architecture . 206Info.plist and NSDocumentController . 207NSDocument . 207NSWindowController . 210Saving and NSKeyedArchiver . 211Loading and NSKeyedUnarchiver . 211Setting the Extension and Icon for the File Type . 212Application Data and URLs . 215For the More Curious: Preventing Infinite Loops . 216For the More Curious: Creating a Protocol . 217For the More Curious: Automatic Document Saving . 218For the More Curious: Document-Based Applications Without Undo . 218For the More Curious: Universal Type Identifiers . 21813. Basic Core Data . 221Defining the Object Model . 221Configure the Array Controller . 223Add the Views . 225Connections and Bindings . 229How Core Data Works . 234Fetching Objects from the NSManagedObjectContext . 235Persistent Store Types . 236Choosing a Cocoa Persistence Technology . 237Customizing Objects Created by NSArrayController . 237Challenge: Begin Editing on Add . 238Challenge: Implement RaiseMan Using Core Data . 23814. User Defaults . 239NSUserDefaults . 239Adding User Defaults to SpeakLine . 240Create Names for the Defaults . 241Register Factory Defaults for the Preferences . 241Reading the Preferences . 242Reflecting the Preferences in the UI . 243Writing the Preferences to User Defaults . 243Storing the User Defaults . 244What Can Be Stored in NSUserDefaults? . 245Precedence of Types of Defaults . 246What is the User’s Defaults Database? . 246For the More Curious: Reading/Writing Defaults from the Command Line . 247xi

Cocoa Programming for OS X15.16.17.18.xiiFor the More Curious: NSUserDefaultsController . 248Challenge: Reset Preferences .

Thanks to the students who took the Cocoa programming course at the Big Nerd Ranch. They helped us work the kinks out of the exercises and explanations that appear here. Their curiosity inspired us to make the book more comprehensive, and their patience made it possible.