You are previewing Cocoa Programming for OS X: The Big Nerd Ranch Guide.
O'Reilly logo
Cocoa Programming for OS X: The Big Nerd Ranch Guide

Book Description

Covering the bulk of what you need to know to develop full-featured applications for OS X, this edition is updated for OS X Yosemite (10.10),  Xcode 6, and Swift. Written in an engaging tutorial style and class-tested for clarity and accuracy, it is an invaluable resource for any Mac programmer. The authors introduce the two most commonly used Mac developer tools: Xcode and Instruments. They also cover the Swift language, basic application architecture, and the major design patterns of Cocoa. Examples are illustrated 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.

This edition was written for Xcode 6.3 and Swift 1.2. At WWDC 2015, Apple announced Xcode 7 and Swift 2, both of which introduce significant updates that (along with some changes to Cocoa for OS X 10.11) affect some of the exercises in this book. We have prepared a companion guide listing the changes needed to use Xcode 7 to work through the exercises in the book; it is available at https://github.com/bignerdranch/cocoa-programming-for-osx-5e/blob/master/Swift2.md.

Table of Contents

  1. Title Page
  2. Dedication
  3. Acknowledgments
  4. Table of Contents
  5. Introduction
    1. About This Book
      1. Prerequisites
      2. Typographical conventions
      3. Using an eBook
      4. What’s new in the fifth edition?
    2. The Story of Cocoa
      1. NeXTSTEP and OpenStep
      2. From NeXTSTEP to OS X to iOS
      3. OSX, Unix, and Cocoa
    3. Introducing the Swift Language
    4. The Cocoa Frameworks
    5. Tools for Cocoa Programming
    6. Some Advice on Learning
  6. 1. Let’s Get Started
    1. Creating an Xcode Project
      1. Getting around in Xcode
    2. Application Design
      1. Model-View-Controller
        1. The view layer
        2. The model layer
        3. The controller layer
      2. Creating the MainWindowController class
    3. Creating the User Interface in Interface Builder
      1. Adding view objects
      2. Configuring view objects
      3. XIB files and NIB files
    4. Showing the Window
    5. Making Connections
      1. Creating an outlet
      2. Connecting an outlet
      3. Defining an action method
      4. Connecting actions
    6. Creating the Model Layer
    7. Connecting the Model Layer to the Controller
    8. Improving Controller Design
  7. 2. Swift Types
    1. Introducing Swift
    2. Types in Swift
    3. Using Standard Types
      1. Inferring types
      2. Specifying types
        1. Number and boolean types
        2. Collection types
      3. Literals and subscripting
      4. Initializers
      5. Properties
      6. Instance methods
    4. Optionals
      1. Subscripting dictionaries
    5. Loops and String Interpolation
    6. Enumerations and the Switch Statement
      1. Enumerations and raw values
    7. Exploring Apple’s Swift Documentation
  8. 3. Structures and Classes
    1. Structures
      1. Instance methods
        1. Using self in instance methods
    2. Operator Overloading
    3. Classes
      1. Designated and convenience initializers
      2. Add an instance method
      3. Inheritance
    4. Computed Properties
    5. Reference and Value Types
      1. Implications of reference and value types
      2. Choosing between reference and value types
    6. Making Types Printable
    7. Swift and Objective-C
    8. Working with Foundation Types
      1. Basic bridging
      2. Bridging with collections
    9. Runtime Errors
    10. More Exploring of Apple’s Swift Documentation
    11. Challenge: Safe Landing
    12. Challenge: Vector Angle
  9. 4. Memory Management
    1. Automatic Reference Counting
      1. Objects have reference counts
      2. Deallocating objects in a hierarchy
    2. Strong and Weak References
      1. Strong reference cycles
      2. Unowned references
    3. What is ARC?
  10. 5. Controls
    1. Setting up RGBWell
      1. Creating the MainWindowController class
      2. Creating an empty XIB file
      3. Creating an instance of MainWindowController
      4. Connecting a window controller and its window
        1. File's Owner and making connections
    2. About Controls
    3. Working with Controls
      1. A word about NSCell
      2. Connecting the slider’s target and action
      3. A continuous control
      4. Setting the slider’s range values
      5. Adding two more sliders
      6. NSColorWell and NSColor
      7. Disabling a control
    4. Using the Documentation
      1. Changing the color of the color well
    5. Controls and Outlets
      1. Implicitly unwrapped optionals
    6. For the More Curious: More on NSColor
    7. For the More Curious: Setting the Target Programmatically
    8. Challenge: Busy Board
    9. Debugging Hints
  11. 6. Delegation
    1. Setting up SpeakLine
      1. Creating and using an Xcode snippet
      2. Creating the user interface
    2. Synthesizing Speech
    3. Updating Buttons
    4. Delegation
      1. Being a delegate
        1. Conforming to a protocol
        2. Implementing a delegate method
        3. Setting the delegate property
      2. Implementing another delegate
      3. Common errors in implementing a delegate
      4. Cocoa classes that have delegates
      5. Delegate protocols and notifications
    5. NSApplication and NSApplicationDelegate
      1. The main event loop
    6. For the More Curious: How Optional Delegate Methods Work
    7. Challenge: Enforcing a Window’s Aspect Ratio
  12. 7. Working with Table Views
    1. About Table Views
      1. Delegates and data sources
      2. The table view-data source conversation
      3. SpeakLine’s table view and helper objects
    2. Getting Voice Data
      1. Retrieving friendly names
    3. Adding a Table View
      1. Table view and related objects
        1. Table columns
        2. Disabling resizing of the window
    4. Tables, Cells, and Views
      1. Table cell views
    5. The NSTableViewDataSource Protocol
      1. Conforming to the protocol
      2. Connecting the dataSource outlet
      3. Implementing data source methods
      4. Binding the text field to the table cell view
    6. The NSTableViewDelegate Protocol
      1. Making a connection with the assistant editor
      2. Implementing a delegate method
      3. Pre-selecting the default voice
    7. Challenge: Make a Data Source
  13. 8. KVC, KVO, and Bindings
    1. Bindings
      1. Setting up Thermostat
      2. Using bindings
      3. Key-value observing
      4. Making keys observable
      5. Binding other attributes
    2. KVC and Property Accessors
    3. KVC and nil
    4. Debugging Bindings
    5. Using the Debugger
      1. Using breakpoints
      2. Stepping through code
        1. Deleting breakpoints
        2. Setting an exception breakpoint
      3. The LLDB console
      4. Using the debugger to see bindings in action
    6. For the More Curious: Key Paths
    7. For the More Curious: More on Key-Value Observing
    8. For the More Curious: Dependent Keys
    9. Challenge: Convert RGBWell to Use Bindings
  14. 9. NSArrayController
    1. RaiseMan’s Model Layer
    2. RaiseMan’s View Layer
    3. Introducing NSArrayController
    4. Adding an Array Controller to the XIB
    5. Binding the Array Controller to the Model
    6. Binding the Table View’s Content to the Array Controller
    7. Connecting the Add Employee Button
    8. Binding the Text Fields to the Table Cell Views
    9. Formatting the Raise Text Field
    10. Connecting the Remove Button
    11. Binding the Table View’s Selection to the Array Controller
    12. Configuring RaiseMan’s Remove Button
    13. Sorting in RaiseMan
    14. How Sorting Works in RaiseMan
    15. For the More Curious: The caseInsensitiveCompare(_:) Method
    16. For the More Curious: Sorting Without NSArrayController
    17. For the More Curious: Filtering
    18. For the More Curious: Using Interface Builder’s View Hierarchy Popover
    19. Challenge: Sorting Names by Length
  15. 10. Formatters and Validation
    1. Formatters
      1. Formatters, programmatically
      2. Formatters and a control’s objectValue
      3. Formatters and localization
    2. Validation with Key-Value Coding
      1. Adding Key-Value validation to RaiseMan
    3. For the More Curious: NSValueTransformer
  16. 11. NSUndoManager
    1. Message Passing and NSInvocation
    2. How the NSUndoManager Works
    3. Using NSUndoManager
    4. Key-Value Coding and To-Many Relationships
    5. Adding Undo to RaiseMan
    6. Key-Value Observing
    7. Using the Context Pointer Defensively
    8. Undo for Edits
    9. Begin Editing on Insert
    10. For the More Curious: Windows and the Undo Manager
  17. 12. Archiving
    1. NSCoder and NSCoding
      1. Encoding
      2. Decoding
    2. The Document Architecture
      1. Info.plist and NSDocumentController
      2. NSDocument
        1. Saving documents
          1. Understanding NSErrorPointer
        2. Loading documents
      3. NSWindowController
    3. Saving and NSKeyedArchiver
    4. Loading and NSKeyedUnarchiver
    5. Setting the Extension and Icon for the File Type
    6. Application Data and URLs
    7. For the More Curious: Preventing Infinite Loops
    8. For the More Curious: Creating a Protocol
    9. For the More Curious: Automatic Document Saving
    10. For the More Curious: Document-Based Applications Without Undo
    11. For the More Curious: Universal Type Identifiers
  18. 13. Basic Core Data
    1. Defining the Object Model
    2. Configure the Array Controller
    3. Add the Views
    4. Connections and Bindings
    5. How Core Data Works
    6. Fetching Objects from the NSManagedObjectContext
    7. Persistent Store Types
    8. Choosing a Cocoa Persistence Technology
    9. Customizing Objects Created by NSArrayController
    10. Challenge: Begin Editing on Add
    11. Challenge: Implement RaiseMan Using Core Data
  19. 14. User Defaults
    1. NSUserDefaults
    2. Adding User Defaults to SpeakLine
    3. Create Names for the Defaults
    4. Register Factory Defaults for the Preferences
    5. Reading the Preferences
    6. Reflecting the Preferences in the UI
    7. Writing the Preferences to User Defaults
    8. Storing the User Defaults
    9. What Can Be Stored in NSUserDefaults?
    10. Precedence of Types of Defaults
    11. What is the User’s Defaults Database?
    12. For the More Curious: Reading/Writing Defaults from the Command Line
    13. For the More Curious: NSUserDefaultsController
    14. Challenge: Reset Preferences
  20. 15. Alerts and Closures
    1. NSAlert
    2. Modals and Sheets
    3. Completion Handlers and Closures
      1. Closures and capturing
    4. Make the User Confirm the Deletion
    5. For the More Curious: Functional Methods and Minimizing Closure Syntax
    6. Challenge: Don’t Fire Them Quite Yet
    7. Challenge: Different Messages for Different Situations
  21. 16. Using Notifications
    1. What Notifications Are
    2. What Notifications Are Not
    3. NSNotification
    4. NSNotificationCenter
    5. Starting the Chatter Application
    6. Using Notifications in Chatter
    7. For the More Curious: Delegates and Notifications
    8. Challenge: Beep-beep!
    9. Challenge: Add Usernames
    10. Challenge: Colored Text
    11. Challenge: Disabling the Send Button
  22. 17. NSView and Drawing
    1. Setting Up the Dice Application
      1. Creating a view subclass
    2. Views, Rectangles, and Coordinate Systems
      1. frame
      2. bounds
    3. Custom Drawing
      1. drawRect(_:)
      2. When is my view drawn?
      3. Graphics contexts and states
      4. Drawing a die face
        1. Drawing the die profile
        2. Drawing the dots
          1. Dot positioning and drawing
    4. Saving and Restoring the Graphics State
    5. Cleaning up with Auto Layout
    6. Drawing Images
      1. Inspectable properties and designable views
      2. Drawing images with finer control
    7. Scroll Views
    8. Creating Views Programmatically
    9. For the More Curious: Core Graphics and Quartz
    10. For the More Curious: Dirty Rects
    11. For the More Curious: Flipped Views
    12. Challenge: Gradients
    13. Challenge: Stroke
    14. Challenge: Make DieView Configurable from Interface Builder
  23. 18. Mouse Events
    1. NSResponder
    2. NSEvent
    3. Getting Mouse Events
    4. Click to Roll
    5. Improving Hit Detection
    6. Gesture Recognizers
    7. Challenge: NSBezierPath-based Hit Testing
    8. Challenge: A Drawing App
  24. 19. Keyboard Events
    1. NSResponder
    2. NSEvent
    3. Adding Keyboard Input to DieView
      1. Accept first responder
      2. Receive keyboard events
      3. Putting the dice in Dice
    4. Focus Rings
    5. The Key View Loop
    6. For the More Curious: Rollovers
  25. 20. Drawing Text with Attributes
    1. NSFont
    2. NSAttributedString
    3. Drawing Strings and Attributed Strings
    4. Drawing Text Die Faces
      1. Extensions
    5. Getting Your View to Generate PDF Data
    6. For the More Curious: NSFontManager
    7. Challenge: Color Text as SpeakLine Speaks It
  26. 21. Pasteboards and Nil-Targeted Actions
    1. NSPasteboard
    2. Add Cut, Copy, and Paste to Dice
    3. Nil-Targeted Actions
      1. Looking at the XIB file
    4. Menu Item Validation
    5. For the More Curious: Which Object Sends the Action Message?
    6. For the More Curious: UTIs and the Pasteboard
      1. Custom UTIs
    7. For the More Curious: Lazy Copying
    8. Challenge: Write Multiple Representations
    9. Challenge: Menu Item
  27. 22. Drag-and-Drop
    1. Make DieView a Drag Source
      1. Starting a drag
      2. After the drop
    2. Make DieView a Drag Destination
      1. registerForDraggedTypes(_:)
      2. Add highlighting
      3. Implement the dragging destination methods
    3. For the More Curious: Operation Mask
  28. 23. NSTimer
    1. NSTimer-based Animation
    2. How Timers Work
    3. NSTimer and Strong/Weak References
    4. For the More Curious: NSRunLoop
  29. 24. Sheets
    1. Adding a Sheet
    2. Create the Window Controller
    3. Set Up the Menu Item
    4. Lay Out the Interface
    5. Configuring the Die Views
    6. Present the Sheet
    7. Modal Windows
    8. Encapsulating Presentation APIs
    9. Challenge: Encapsulate Sheet Presentation
    10. Challenge: Add Menu Item Validation
  30. 25. Auto Layout
    1. What is Auto Layout?
    2. Adding Constraints to RaiseMan
      1. Constraints from subview to superview
      2. Constraints between siblings
      3. Size constraints
    3. Intrinsic Content Size
    4. Creating Layout Constraints Programmatically
    5. Visual Format Language
    6. Does Not Compute, Part 1: Unsatisfiable Constraints
    7. Does Not Compute, Part 2: Ambiguous Layout
    8. For the More Curious: Autoresizing Masks
    9. Challenge: Add Vertical Constraints
    10. Challenge: Add Constraints Programmatically
  31. 26. Localization and Bundles
    1. Different Mechanisms for Localization
    2. Localizing a XIB File
    3. Localizing String Literals
    4. Demystifying NSLocalizedString and genstrings
    5. Explicit Ordering of Tokens in Format Strings
    6. NSBundle
      1. NSBundle’s role in localization
      2. Loading code from bundles
    7. For the More Curious: Localization and Plurality
    8. Challenge: Localizing the Default Name for a Newly Added Employee
    9. Challenge: Localizing the Undo Action Names
  32. 27. Printing
    1. Dealing with Pagination
    2. Adding Printing to RaiseMan
    3. For the More Curious: Are You Drawing to the Screen?
    4. Challenge: Add Page Numbers
    5. Challenge: Persist Page Setup
  33. 28. Web Services
    1. Web Services APIs
    2. RanchForecast Project
      1. NSURLSession and asynchronous API design
      2. NSURLSession, HTTP status codes, and errors
      3. Add JSON parsing to ScheduleFetcher
      4. Lay out the interface
    3. Opening URLs
    4. Safely Working with Untyped Data Structures
    5. For the More Curious: Parsing XML
    6. Challenge: Improve Error Handling
    7. Challenge: Add a Spinner
    8. Challenge: Parse the XML Courses Feed
  34. 29. Unit Testing
    1. Testing in Xcode
    2. Your First Test
    3. A Note on Literals in Testing
    4. Creating a Consistent Testing Environment
    5. Sharing Constants
    6. Refactoring for Testing
    7. For the More Curious: Access Modifiers
    8. For the More Curious: Asynchronous Testing
    9. Challenge: Make Course Implement Equatable
    10. Challenge: Improve Test Coverage of Web Service Responses
    11. Challenge: Test Invalid JSON Dictionary
  35. 30. View Controllers
    1. NSViewController
    2. Starting the ViewControl Application
    3. Windows, Controllers, and Memory Management
    4. Container View Controllers
    5. Add a Tab View Controller
    6. View Controllers vs. Window Controllers
    7. Considerations for OS X 10.9 and Earlier
    8. Challenge: SpeakLineViewController
    9. Challenge: Programmatic View Controller
    10. Challenge: Add a Window Controller
  36. 31. View Swapping and Custom Container View Controllers
    1. View Swapping
    2. NerdTabViewController
    3. Adding Tab Images
    4. Challenge: Boxless NerdTabViewController
    5. Challenge: NerdSplitViewController
    6. Challenge: Draggable Divider
  37. 32. Storyboards
    1. A New UI for RanchForecast
      1. Adding the course list
      2. Adding the web view
    2. Connecting the Course List Selection with the Web View
      1. Creating the CourseListViewControllerDelegate
      2. Creating the parent view controller
    3. For the More Curious: How is the Storyboard Loaded?
  38. 33. Core Animation
    1. CALayer
    2. Scattered
    3. Implicit Animation and Actions
    4. More on CALayer
    5. Challenge: Show Filenames
    6. Challenge: Reposition Image Layers
  39. 34. Concurrency
    1. Multithreading
    2. A Deep Chasm Opens Before You
    3. Improving Scattered: Time Profiling in Instruments
      1. Introducing Instruments
      2. Analyzing output from Instruments
    4. NSOperationQueue
      1. Multithreaded Scattered
      2. Thread synchronization
    5. For the More Curious: Faster Scattered
    6. Challenge: An Even Better Scattered
  40. 35. NSTask
    1. ZIPspector
    2. Asynchronous Reads
    3. iPing
    4. Challenge: .tar and .tgz Files
  41. 36. Distributing Your App
    1. Build Configurations
    2. Preprocessor Directives: Using Build Configurations to Change Behavior
    3. Creating a Release Build
    4. A Few Words on Installers
    5. App Sandbox
      1. Entitlements
      2. Containers
      3. Mediated file access and Powerbox
    6. The Mac App Store
    7. Receipt Validation
      1. Local receipt verification
      2. Server-based verification
  42. 37. Afterword
  43. Index