O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Learning Cocoa

Book Description

Cocoa™ is one of the principal application environments for Mac® OS X. Among Cocoa's many attributes, its advanced object-oriented APIs allow you to develop in both Java and Objective-C. This revolutionary new way of developing sophisticated applications for the Macintosh is both powerful and easy. With Learning Cocoa you'll become familiar with Cocoa application development, using Objective C, not merely by reading, but by doing. The book begins with a discussion of essential object-oriented programming concepts for those with no previous experience. It proceeds through an introduction to the Cocoa environment, development, tools, and some simple tutorials to help you become familiar with the basic elements of Cocoa programming. The remaining tutorials guide you as you create a series of increasingly complex example applications. The techniques and concepts you learn in one tutorial lay the foundation for the more advanced techniques and concepts in the next. You don't need extensive programming experience to complete the examples in this book, though it would be helpful to have some experience with the C programming language. The code for each example is included in the text so you can simply type it in. If you're already familiar with an object-oriented programming language like Java or Smalltalk, you'll quickly feel right at home with Objective-C, the language used throughout this book. As you ease your way into the experience of Cocoa programming, you're encouraged to play, to explore, to "kick the tires." You'll finish this book much better prepared to take on serious application development with Cocoa, and you'll find Apple's development environment not only less mysterious, but one that you'll be eager to program in. Written by insiders at Apple Computer, the book brings you information that you can't get anywhere else--and a potential leg up in the Mac OS X application development market.

Table of Contents

  1. Learning Cocoa
    1. Preface
      1. Organization of This Book
        1. Part I, Cocoa Overview
        2. Part II, Single-Window Applications
        3. Part III, Multiple-Window Applications
      2. Conventions Used in This Book
      3. How to Contact Us
    2. I. Cocoa Overview
      1. 1. Introduction to Cocoa
        1. Cocoa Features
          1. Imaging and Printing Model
          2. Multimedia
            1. QuickTime
            2. OpenGL
          3. Internet
          4. Localization and Internationalization
          5. Text and Fonts
          6. Component Technologies
        2. The Cocoa Frameworks
          1. Foundation
            1. Programming types and operations
              1. Collections
              2. Dates and times
              3. Strings and text
              4. Data and values
              5. String scanning
              6. Exception handling
            2. Operating system entities and services
              1. Notifications
              2. Threads
              3. Locks
              4. Tasks
              5. Ports
              6. Run loops
              7. Timers
            3. Object functionality
              1. Memory management
              2. Distributed objects
              3. Serialization and archiving
            4. File and I/O management
              1. URL handling
            5. Other services
          2. Application Kit
            1. User interface
              1. Windows
              3. Panels
              4. Controls
            2. Feature integration
              1. Text and fonts
              2. Images
              3. Color
            3. Facilities
              1. Document architecture
              2. Responder chain
              3. Sharing data with other applications
              4. Drag and drop
              5. Printing
              6. Accessing the file system
              7. Spellchecking
              8. Localization
      2. 2. Object-Oriented Programming
        1. The Advantages of Object-Oriented Programming
          1. Programming with Objects
        2. Fundamental Object-Oriented Concepts
          1. Objects
          2. Encapsulation
          3. Classes
          4. Methods and Messages
          5. Polymorphism and Dynamic Binding
          6. Inheritance
      3. 3. Objective-C Primer
        1. Language Summary
          1. Messages
          2. Defined Types
          3. Preprocessor Directives
          4. Compiler Directives
          5. Classes
          6. Categories
          7. Protocols
          8. Method Declarations
          9. Method Implementations
          10. Naming Conventions
        2. Objective-C in Action
          1. Declarations
          2. Messages and Method Implementations
          3. Defining a Class
          4. Overriding a Method
          5. Object Creation
            1. Designated initializers
      4. 4. Development Tools
        1. Project Builder
          1. Feature Highlights
            1. Delimiter checking
            2. Emacs key bindings
            3. Find
            4. Flexible build system
        2. Interface Builder
        3. Other Development Tools
        4. Useful Command-Line Tools
    3. II. Single-Window Applications
      1. 5. Hello World
        1. Creating the Project
          1. Open Project Builder
          2. Choose the New Project Command
          3. Select Project Type
          4. The Main Window
          5. Build the Application
      2. 6. Essential Cocoa Paradigms
        1. Cocoa’s Collection Classes
          1. Working with NSArray
          2. Working with NSDictionary
            1. Working with dictionaries
        2. Create Graphical User Interfaces in Cocoa
          1. Windows in Cocoa
            1. NSWindow and the window server
            2. Application, window, and view
            3. Key and main windows
          2. Nib Files
          3. Outlets
          4. Create a Cocoa Application Project
          5. Open the Main Nib File
          6. Move and Resize the Window
          7. Add a Text Field
          8. Create a Custom Subclass
          9. Define an Outlet for the Class
          10. Generate an Instance of the Class
          11. Connect the Custom Class to the Interface
          12. Generate the Source Files
          13. Examine a Header File in Project Builder
          14. Statically Type the Outlet
          15. Implement MyController’s awakeFromNib Method
          16. Build, Debug, and Run Nib Files
            1. Build the project
            2. Debug the project
            3. Run the application
        3. Controls, Cells, and Formatters
          1. Cells and Formatters
          2. A Formatted Cell Example
        4. Target/Action
          1. Target/Action Example
            1. Create the project and user interface
            2. Create the controller class
            3. Define the outlets of the class
            4. Define an action for the class
            5. Generate an instance of the class
            6. Connect the interface controls to the class’s actions
            7. Connect the custom class to the interface
            8. Generate the source files
            9. Implement MyController’s action method
            10. Build and debug the application
        5. Object Ownership, Retention, and Disposal
          1. Object Initialization and Deallocation
          2. Reference Counting
          3. Autorelease Pools
          4. Implications of Retained Objects
          5. Copying Versus Retaining
          6. Reference Counting in Accessors
            1. When to release
            2. When to copy
            3. Release or autorelease
          7. Tips for Eliminating Deallocation Bugs
      3. 7. Currency Converter Tutorial
        1. Design the Currency Converter Application
          1. The Model-View-Controller (MVC) Paradigm
            1. MVC in Currency Converter’s design
        2. Create the Currency Converter Project
          1. Create the Application Project
          2. Project Indexing
        3. Create the Currency Converter Interface
          1. Open the Main Nib File
          2. Resize the Window
          3. Set the Window’s Title and Attributes
          4. Place a Text Field; Resize and Initialize It
          5. Duplicate an Object
          6. Change the Attributes of a Text Field
          7. Assign Labels to the Fields
          8. Add a Button to the Interface and Initialize It
          9. Add a Horizontal Decorative Line
          10. Aqua Layout and Object Alignment
          11. Center the Interface Objects and Resize the Window
          12. Enable Tabbing Between Text Fields
          13. Test the Interface
        4. Define the Classes of Currency Converter
          1. Create the ConverterController Subclass
          2. Define Outlets for ConverterController
          3. Define Actions for ConverterController
          4. Define the Converter Class
        5. Connect ConverterController to the Interface
          1. Generate an Instance of the Class
          2. Connect the Custom Class to the Interface
          3. Connect the Interface Controls to the Class’s Actions
          4. Connect ConverterController to the Converter Class
        6. Implement the Classes of Currency Converter
          1. Generate the Source Files
          2. Examine an Interface (Header) File in Project Builder
          3. Add a Method Declaration
          4. Implement Currency Converter’s Classes
          5. Build and Run Currency Converter
            1. Build the project
            2. Run Currency Converter
      4. 8. Event Handling
        1. Respond to User-Generated Events
          1. The Application Quartet
            1. NSResponder
            2. NSWindow
            3. NSView
            4. NSApplication
          2. The View Hierarchy
            1. Subclass NSView
          3. The Event Cycle and First Responder
            1. The event queue and event dispatching
            2. Event types and tracing
            3. First responder and the responder chain
              1. Key window and first responder
          4. Create the Dot View Application
        2. Respond to Program-Generated Events
          1. Delegation
            1. A simple delegate example
              1. Use sheets
              2. Find delegate methods programmatically
          2. Notification
            1. Register to receive a notification
            2. A simple notification example
              1. Create a new project
              2. Add a text field and controller class
              3. Make MyController an observer
              4. Build and run the application
      5. 9. Data Functionality
        1. Table Views and Data Sources
          1. A Very Simple Table
            1. Create the project
            2. Add the table view
            3. Configure the table columns
            4. Declare the data source class
            5. Implement the data source methods
            6. Build and run the project
          2. A More Complete Table View Example
            1. Create an expense class
            2. Add a new column to the table view
            3. Configure the table columns
            4. Add table column identifiers
            5. Update the data source class
            6. Seed the Expense array with test data
            7. Build and test the application
            8. Modify values in the table view
            9. Enter data in the table view
          3. Further Exploration
        2. Flatten the Object Network: Coding and Archiving
          1. NSCoder and NSArchiver
          2. Add Coding and Archiving to the Expenses Application
      6. 10. Travel Advisor Tutorial
        1. Travel Advisor Design
          1. Model Objects
          2. View Objects
          3. Controller Objects
            1. How TAController manages data
            2. Storing data source information
            3. Creation of Country objects
            4. Delegation and notification
        2. Create the Travel Advisor Interface
          1. Get Started
          2. Create the Application Project
          3. Customize the Application Window
          4. Add the Text Fields, Labels, and Buttons to the Window
            1. More about buttons
          5. Add a Form Object to the Interface
          6. Group the Objects on the Interface
          7. Add the Text View
          8. Add and Configure the Table View
          9. Add an Image to the Interface
          10. Add a Menu and Menu Items
          11. Add Formatters
          12. Make Connections for InterfieldTabbing and Printing
          13. Test the Interface
        3. Define the Classes of Travel Advisor
          1. Specify the Country and TAController Classes
          2. Specify TAController’s Outlets and Actions
          3. Reuse the Converter Class
          4. Generate TAController and Converter Instances
          5. Make Connections to the TAController Instance
          6. View Connections in Outline Mode
          7. About File’s Owner
          8. Connect the Delegate Outlet
          9. Generate Source Code Files
        4. Implement the Classes of Travel Advisor
          1. Reuse Currency Converter
          2. Build and Test the Application
          3. Implement Temperature Conversion
          4. Implement the Country Class
            1. Declare instance variables
            2. Methods for the Country class
              1. Declare the Methods
            3. Implement the Country object’s init method
            4. Implement the dealloc method
            5. Implement the accessor methods
          5. Statically Type TAController’s Outlets
          6. Add New Instance Variables to TAController.h
          7. Implement the blankFields: Method
          8. TAController and Data Mediation
            1. Implement the extractFields: method
            2. Implement the populateFields: method
          9. Get the Table View to Work
            1. Implement the behavior of the table view’s data source
            2. Implement two methods of the NSTableDataSource informal protocol
            3. Implement the country-selection method
            4. Optional exercise
          10. Build the Project
          11. Add and Delete Records
          12. Field Validation
          13. Application Management
            1. Implement TAController’s methods for initializing and deallocating itself
            2. Implement notification to track modified records
          14. Implement Archiving and Unarchiving
          15. Build and Run the Application
    4. III. Multiple-Window Applications
      1. 11. Cocoa’s Multiple-Document Architecture
        1. Architectural Overview
          1. The Role of NSDocumentController
          2. The Role of NSDocument
          3. The Role of NSWindowController
        2. Implement a Document-Based Application
          1. The Document-Based Application Package
          2. Create the Project
          3. Compose the Interface
          4. Modify the Info Property List
          5. Subclass NSDocument
            1. Data-based primitives
            2. Location-based primitives
            3. Window controller creation
            4. Printing and page layout
            5. Backup files
            6. Menu items
            7. Initializers
          6. Implement the NSDocument Subclass
      2. 12. To Do: Basics
        1. The Design of To Do
          1. To Do’s Multidocument Design
          2. How To Do Stores and Accesses Its Data
          3. To Do’s Custom Views
          4. About Dates and Times in Cocoa
        2. Build the Application
          1. Create the Project
          2. Rename the NSDocument Subclass
          3. Create the Model Class (ToDoItem)
            1. Declare the instance variables
            2. Declare methods
            3. Define constants
            4. Declare time-conversion functions
            5. Implement accessor methods
            6. Implement a description method
            7. Implement init and dealloc
            8. Implement archiving and unarchiving
            9. Implement time conversion
          4. Implement the Calendar view
            1. Matrix as superclass
            2. Compose the interface
            3. Add declarations to the header file
            4. Declare CalendarMatrix’s private methods
            5. Implement initWithFrame: and dealloc
            6. Implement awakeFromNib
            7. Implement refreshCalendar
            8. Implement highlightTodayIfVisible
            9. Implement the choseDay: action method
            10. Implement the monthChanged: action method
            11. Build and test
          5. Complete the Document Interface
            1. Implement init and dealloc
            2. Implement accessor and action methods
            3. Implement ToDoDocument’s delegate methods
            4. Build and test
          6. Manage To Do’s Data and Coordinate Its Display
            1. Declare ToDoDocument’s private methods
            2. Modify windowControllerDidLoadNib:
            3. Implement initDataModelWithDictionary:
            4. Implement the currentItems accessor methods
            5. Implement updateLists:
            6. Implement saveDocItems:
            7. Implement selectItemAtRow:
            8. Implement controlTextDidBeginEditing:
            9. Implement controlTextDidEndEditing:
            10. Update the CalendarMatrix delegate method
            11. Build and test
      3. 13. To Do: Extended
        1. Create and Manage an Info Window
          1. Customize the Application’s Menu
          2. Create and Configure an Application Delegate
          3. Create a nib File for To Do’s Info Window
          4. Create an Offscreen Panel
          5. Apply Formatters
          6. Define the InfoWindowController Class
          7. Type Outlets
          8. Add Declarations to InfoWindowController.h
          9. Implement Basic Methods
            1. Import headers
            2. Add private declarations
            3. Implement the class method sharedInfoWindowController
            4. Implement init, windowDidLoad, and dealloc
            5. Add a Stub for the updateInfoWindow Method
            6. Implement setMainWindow:
            7. Implement mainWindowChanged:
            8. Implement swapInfoWindowView:
          10. Build and Test
          11. Implement Advanced InfoWindowController Methods
            1. Implement updateInfoWindow
            2. Implement clearButtonMatrix
            3. Implement switchClicked:
            4. Implement notification methods
        2. Create SelectionNotifyMatrix
          1. Create Files for SelectionNotifyMatrix
          2. Override mouseDown:
          3. Override selectCellAtRow:column:
          4. Reassign the Class of the itemList Matrix
          5. Respond to the Notification
        3. Data Synchronization
        4. Create a Custom View to Display ToDoItem Status
          1. Why Choose NSButtonCell as a Superclass?
          2. Implement the ToDoCell Interface
          3. Declare Private Methods
          4. Implement init and dealloc
          5. Implement Accessor Methods
          6. Set the Cell Image
          7. Track Mouse Clicks
          8. Get and Set the Time Due
          9. Create and Install the Custom Cells
          10. Respond to Mouse Clicks
        5. Set Up Timers
          1. Set a Timer for an Item
          2. Implement setTimerForItem:
          3. Respond to Timers
          4. Build and Test
        6. Implement Archiving and Unarchiving (Save and Open)
          1. Implement dataRepresentationOfType:
          2. Implement loadDataRepresentation:ofType:
          3. Modify windowControllerDidLoadNib:
          4. Implement loadDocWithData:
          5. Build and Test
            1. Optional exercises
      4. 14. To Do: Finishing Touches
        1. Configure Application Settings
          1. Specify a Bundle Identifier
          2. Specify an Application Signature
          3. Specify Display Information
        2. Add an Application Icon
        3. Define a Document Type for To Do
        4. Enable Compiler Optimization
    5. IV. Reference
      1. A. Drawing in Cocoa
        1. Coordinate Systems
        2. Transformation Matrices
        3. NSView
          1. Frame and bounds
          2. Focus
          3. Composite Images
        4. Draw NSStrings
        5. NSBezierPath
          1. Construct Paths
          2. Path Elements
          3. Draw Paths
        6. Draw with NSBezierPath
          1. Draw Lines and Rectangles
          2. Draw Complex Shapes
        7. Draw with Quartz Primitives
    6. Index
    7. Colophon