BUY THIS BOOK

Safari Books Online

What is this?

Looking to Reprint this content?


Learning Cocoa
Learning Cocoa By Apple Computer, Inc.
May 2001
Pages: 382

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introduction to Cocoa
Cocoa is an extensive library of reusable software components used for building applications that run on Mac OS X. You can think of Cocoa as a large set of application building blocks that you can use "off the shelf" or adapt for your specific needs. This chapter gives you a high-level overview of those building blocks, shows you how they are organized, and explains the features they provide.
Cocoa poses a learning curve for newcomers, but once you learn to use it, application development will suddenly seem far easier and more fun. Because the Cocoa frameworks give you so much fundamental application functionality "for free," you can spend your time and creative energy building new technology, not reinventing the wheel.
Cocoa has actually been around a long time—almost as long as the Macintosh itself. That's because it is to a large extent based on OpenStep, which as NeXTSTEP was introduced in 1987. OpenStep evolved through many releases, was adopted by many companies as their development and deployment environment of choice, and received glowing reviews in the press. It was, and continues to be, solid technology, based on a design that was years ahead of anything else in the market and it has been perfected year after year.
Let's take a closer look at Cocoa's features and frameworks to give you a better idea of how to use Cocoa to create various applications. Figure 1.1 shows the general structure of the Mac OS X system software.
Figure 1.1: Cocoa is part of Mac OS X's system software
Cocoa is one of the principal application environments for Mac OS X. Cocoa's advanced object-oriented APIs allow you to develop applications written in Java and Objective-C. Cocoa is an integrated set of shared object libraries, or frameworks, plus a runtime system and development environment that does three principal things:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Cocoa Features
This section describes some of the high-level features available to you when you develop using Cocoa.
The imaging and printing model for Mac OS X is Adobe's Portable Document Format (PDF). Unlike in previous versions of the Mac OS, the same mechanism is used to view and print what appears on the screen. You no longer have to duplicate code to send output both to the screen and to PostScript-based devices. The best of Apple's graphics technologies, including ColorSync and QuickDraw GX typography, is being brought to core graphics.
Cocoa applications can take advantage of some of the most powerful technologies available—QuickTime and OpenGL.

Section 1.1.2.1: QuickTime

Mac OS X comes packaged with the latest version of QuickTime. QuickTime is a powerful multimedia technology used for manipulating, enhancing, and storing video, sound, animation, graphics, text, music, and even 360-degree virtual reality.
QuickTime streaming allows users to view live and video-on-demand movies using the industry-standard protocols RTP (Real-Time Transport Protocol) and RTSP (Real-Time Streaming Protocol). Users can view streaming live broadcasts, previously recorded movies, or a mixture of both. Broadcasts can be either unicast (one-to-one) or multicast (one-to-many).

Section 1.1.2.2: OpenGL

Mac OS X includes Apple's highly optimized implementation of OpenGL as the system API and library for three-dimensional (3D) graphics. OpenGL is an industry-wide standard for developing portable 3D graphics applications. OpenGL is one of the most widely adopted graphics API standards today, which makes code written to OpenGL highly portable. It is specifically designed for games, animation, CAD/CAM, medical imaging, and other applications that need a rich, robust framework for visualizing shapes in two and three dimensions. Mac OS X's version of OpenGL produces consistently high-quality graphical images at a high level of performance.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Cocoa Frameworks
Cocoa has two object-oriented frameworks: Foundation (Foundation.framework) and Application Kit (AppKit.framework), as shown in Figure 1.2.
Figure 1.2: The Cocoa frameworks
The classes in Foundation provide objects and functionality that are the basis, or "foundation," of Cocoa. The classes in Application Kit furnish the objects and behavior that your users see in the user interface, such as windows and buttons, and handle their mouse clicks and key presses. The Application Kit depends directly on Foundation.
The Foundation framework defines a base layer of Objective-C classes. Besides providing a set of useful primitive object classes, it introduces several paradigms that define functionality not covered by the Objective-C language (detailed in Chapter 3). The Foundation Framework is designed with these goals in mind:
  • Provide a set of basic utility classes.
  • Make software development easier by introducing consistent conventions for paradigms such as memory management.
  • Support Unicode strings, object persistence, and file management.
The Foundation framework includes the root object class, classes representing basic data types such as strings and byte arrays, collection classes for storing other objects, classes representing system information like dates and classes representing communication ports. Figure 1.3 shows the features provided by Foundation.
Figure 1.3: The Foundation framework's features
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Object-Oriented Programming
For some Mac OS developers, the most striking adjustment they'll make when they start developing Cocoa programs is not the tool set: it is the shift in mind-set that is required to take full advantage of object-oriented programming (OOP). Instead of thinking in terms of procedures and data, you have to think in terms of objects—discrete programmatic units containing their own data as well as procedures that act on that data.
You can't get far in Cocoa development without a grasp of the basic concepts of object-oriented programming. For those new to this approach to programming, it might seem strange at first glance, but a common reaction after learning a bit more is, "Yes, of course." This chapter presents an overview of object-oriented programming from the particular perspective of Objective-C. For additional background on OOP and Objective-C, see Inside Cocoa: Object-Oriented Programming and the Objective-C Language in /Developer/Documentation/Cocoa.
Learning how to program with objects takes some initial effort, but in a very short time, object-oriented programming begins to seem natural, elegant, and powerful. And, with the rich functionality of the Cocoa frameworks to tap, application development becomes easier—you get a huge number of application features "for free." Programming with objects, especially Cocoa objects, increases your productivity by freeing you from many repetitive coding tasks. You have more time to accomplish what is truly creative.
Object orientation is the software equivalent of the Industrial Revolution. In the same way that modern factories assemble products out of prefabricated components rather than manufacture every product from scratch, object orientation allows programmers to build complex software by reusing software components called objects. Specifically, objects lead to several measurable advantages:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Advantages of Object-Oriented Programming
Object orientation is the software equivalent of the Industrial Revolution. In the same way that modern factories assemble products out of prefabricated components rather than manufacture every product from scratch, object orientation allows programmers to build complex software by reusing software components called objects. Specifically, objects lead to several measurable advantages:
  • Greater reliability. By breaking complex software projects into small, self-contained, and modular objects, object orientation ensures that changes to one part of a software project will not adversely affect other portions of the software. Being small, each of these objects is a well-tested module of code, so the overall reliability of the software increases.
  • Easier maintainability. Since objects are modular and usually small (in terms of the overall code size of a project), bugs in code are easier to locate. Developers can also change the implementation of an object without causing havoc in other parts of an application.
  • Greater productivity through reuse. One of the principal benefits of object orientation is reuse. One object can be integrated into many applications. You can also create new, specialized objects by inheriting functionality from an existing class and then adding new code to modify or extend that class's behavior. This technique reduces coding and promotes greater reliability because the new class implements only the behavior or logic specific to your application. It obtains basic functionality from Cocoa framework objects.
Object-oriented programming delivers its greatest benefits to large and complex programs. But its advantages can also be demonstrated using a very simple example.
With procedural programming techniques, the application is directly responsible for data manipulation. One problem with this is illustrated in Figure 2.1. It shows a data structure consisting of a count variable and a data pointer. Since the application directly manipulates the data, it has the opportunity to introduce inconsistencies. Here, it has added an item to the data but has forgotten to increment the count; the count variable says there are still only two data elements when in fact there are three. The structure has become inconsistent and unreliable.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Fundamental Object-Oriented Concepts
There are only a handful of key concepts that you need to understand to grasp the essence of object-oriented programming. This section presents those key concepts along with Objective-C implementation details, where appropriate.
An object is a self-contained programmatic unit that combines data and the procedures that operate on that data. An object's data is kept in instance variables. The functions that affect or make use of the data in an object's instance variables are known as methods.
Like objects in the physical world, objects in a program have identifying characteristics and behavior. Often, programmatic objects are modeled on real objects. For example, an object such as a button has an analogue in the buttons on control devices, such as stereo equipment and telephones. A button object includes the data and code to generate an appearance on the screen that simulates a "real" button and to respond in a familiar way to user actions.
Just as procedures compartmentalize code, objects compartmentalize both code and data. This results in data encapsulation, effectively surrounding data with the procedures for manipulating that data. Figure 2.4 shows this relationship between an object's data and its methods.
Figure 2.4: An object
Though it might look a bit like a jelly doughnut or a slashed tire, this symbol illustrates data encapsulation, the essential characteristic of objects. Other objects or external code cannot access the encapsulated data directly, but must send messages to the object requesting its data.
Typically, an object is regarded as a black box, meaning that a program never directly accesses an object's variables. Indeed, a program shouldn't even need to know what variables an object has in order to perform its functions. Instead, the program accesses the object only through its methods. In a sense, the methods surround the data, not only shielding an object's instance variables but mediating access to them.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Objective-C Primer
The Objective-C language is a superset of ANSI C with special syntax and runtime extensions that make object-oriented programming possible. Objective-C syntax is uncomplicated, but powerful in its simplicity. You can mix standard C with Objective-C code. Programmers familiar with C and object-oriented programming techniques often find themselves right at home with Objective-C in a matter of days.
This chapter is divided into two main sections. The first section is a basic language summary listing all additions to the language. The second section summarizes some of the most frequently used aspects of the language.
See Inside Cocoa: Object-Oriented Programming and the Objective-C Language in /Developer/Documentation/Cocoa for complete details.
Objective-C adds a small number of constructs to the C language and defines a handful of conventions used to effectively interact with the runtime system.
Message expressions are enclosed in square brackets:
[receiver message]
The receiver can be:
  • A variable or expression that evaluates to an object (including the variable self)
  • A class name (indicating the class object)
  • super (indicating an alternative search for the method implementation)
The message is the name of a method plus any arguments passed to it.
The principal types used in Objective-C are defined in the header file
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Language Summary
Objective-C adds a small number of constructs to the C language and defines a handful of conventions used to effectively interact with the runtime system.
Message expressions are enclosed in square brackets:
[receiver message]
The receiver can be:
  • A variable or expression that evaluates to an object (including the variable self)
  • A class name (indicating the class object)
  • super (indicating an alternative search for the method implementation)
The message is the name of a method plus any arguments passed to it.
The principal types used in Objective-C are defined in the header file objc/objc.h:
TypeDefinition
id
An object (a pointer to its data structure)
Class
A class object (a pointer to the class data structure)
SEL
A selector, a compiler-assigned code that identifies a method name
IMP
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Objective-C in Action
This section touches upon the more frequently used aspects of the Objective-C language, using code snippets where appropriate to illustrate how the language constructs are actually used in the context of an application. Don't worry if you don't completely understand every detail in every section. Objective-C is easy to pick up by example, and you'll have plenty of time to absorb it as you work through the tutorials in the later chapters.
Objects can be declared statically or dynamically. Statically typed objects are declared as a pointer to a class:
NSString *mystring;
Static typing results in better compile-time type checking and makes code easier to understand. Note that in the previous example, mystring doesn't have to be an instance of NSString; it could also be an instance of any class that inherits from NSString.
Dynamically typed objects are declared as id:
id myObject;
Since the class of dynamically typed objects is resolved at runtime, you can refer to them in your code without knowledge of their class membership. Type objects in this way if they are likely to be involved in polymorphism and dynamic binding.
Declarations of instance methods begin with a minus sign (-); a space after the minus sign is optional:
- (NSString *)countryName;
Put the type of value returned by a method in parentheses between the minus sign (or plus sign) and the beginning of the method name. Methods that return nothing should have a return type of void.
Method argument types are in parentheses and go between the argument's keyword and the argument itself:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Development Tools
Apple has a powerful, integrated, cross-platform development environment for Cocoa on Mac OS X. It consists of a suite of applications and tools that deliver maximum productivity from the frameworks, subsystems, libraries, components, and other resources of Mac OS X.
In developing applications with Cocoa, you have a choice of programming languages. You can write programs, in whole or in part, in C, C++, Java, or Objective-C. You can subclass Cocoa classes in Java and mix "pure" Java and Cocoa objects in your code. Note that you cannot access the Cocoa APIs from C++.
In addition to the material provided in this chapter, you can find reference documentation covering the compiler, the debugger, and other tools located in /Developer/Documentation/DeveloperTools.
Project Builder is an application that manages software-development projects and orchestrates and streamlines the development process. Project Builder's key features include:
  • A project browser
  • A full-featured code editor
  • Language-savvy symbol recognition
  • Sophisticated project search capabilities
  • Header file and documentation access
  • Built-in integration with the CVS source-control management system
  • Build customization
  • A graphical source-level debugger
Project Builder's main window is shown in Figure 4.1.
Figure 4.1: The Project Builder main window
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Project Builder
Project Builder is an application that manages software-development projects and orchestrates and streamlines the development process. Project Builder's key features include:
  • A project browser
  • A full-featured code editor
  • Language-savvy symbol recognition
  • Sophisticated project search capabilities
  • Header file and documentation access
  • Built-in integration with the CVS source-control management system
  • Build customization
  • A graphical source-level debugger
Project Builder's main window is shown in Figure 4.1.
Figure 4.1: The Project Builder main window
When you write code with Project Builder you have a set of "workbench" tools at your disposal.

Section 4.1.1.1: Delimiter checking

If you double-click a brace (left or right), the code between the braces (including the delimiters) is highlighted. Similarly, you can double-click a square bracket in a message expression to locate the matching bracket and double-click a parenthesis character to select the enclosing code. If there is no matching delimiter, Project Builder emits a warning beep.

Section 4.1.1.2: Emacs key bindings

Emacs is a popular editor for writing code on Unix platforms. You can use the most common Emacs commands in Project Builder's code editor. For example, there are the commands page forward (Control-V), word forward (Meta-F), delete word (Meta-D), kill forward (Control-K), and yank from kill ring (Control-Y). Some Emacs commands may conflict with some of the standard Macintosh key bindings. You can modify the key bindings Project Builder's code editor uses to substitute other command keys—such as the Option key or Shift-Control—for Emacs' Control or Meta keys. Option (Meta) key bindings are not enabled by default on Mac OS X because the Option key is used to generate special characters. Consult Project Builder's documention for information on using these features.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Interface Builder
Interface Builder makes it easy to create application interfaces. You just drag an object from a palette and drop it on the graphical user interface you're creating (Figure 4.2). You can then set attributes of these objects through an Info window and connect them to other objects in your application so they can send messages to one another. Interface Builder also assists in the definition of custom classes and allows you to test an interface without having to compile a line of code.
Figure 4.2: Interface Builder
Interface Builder's standard palettes hold an assortment of Application Kit objects. Other palettes can include Cocoa objects from other frameworks, third-party objects, and custom-compiled objects. You can also store noncompiled configurations of objects on dynamic palettes. Interface Builder archives and restores elements of a user interface (including connections) as objects—it doesn't "hardwire" them into the interface.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Other Development Tools
In addition to Project Builder and Interface Builder, there are other applications you can use in the Cocoa development process. Development tools featuring a graphical user interface are listed in Table 4.1. Except where noted, these applications are installed in /Developer/Applications.
Table 4.1: Development Tools
NameDescription
FileMerge
Visually compares the contents of two files or two directories. You can use FileMerge, for example, to determine the differences between versions of the same source code file or between two project directories. You can also use it to merge changes.
icns Browser
Displays the entire contents of Mac OS X icon files.
IconComposer
Creates Mac OS X icon files from source art.
IORegistryExplorer
Provides a hierarchical display of the system I/O registry.
JavaBrowser
Displays the Java class hierarchy and documentation.
MallocDebug
Measures the dynamic-memory usage of applications, finds memory leaks, analyzes all allocated memory in an application, and measures the memory allocated since a given time.
MRJAppBuilder
Converts executable Java into double-clickable applications for Mac OS X.
ObjectAlloc
Tracks and displays all object allocations (both Cocoa and Core Foundation) for a running application. Allows you to view the list of objects as well as the call stack that resulted in each allocation.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Useful Command-Line Tools
Apple has created or modified several command-line tools for compilation, debugging, performance analysis, and so on. Table 4.2 lists some of the more useful tools. You can get further information by using the manpages system. The tools are all located in the /usr/bin directory.
Table 4.2: Command-Line Development Tools
NameDescription
cc
Compiles C, Objective-C, and C++ source code files.
gdb
Is a source-level symbolic debugger for C, extended by Apple to support Objective-C and C++.
gnumake
Builds the product(s) of a programming project based on dependency information.
as
Assembles; translates assembly code into object code.
defaults
Reads, writes, searches, and deletes user defaults. The defaults system records user preferences that persist when the application isn't running. When users specify defaults in an application's Preferences panel, NSUserDefaults methods are used to write the defaults.
nibtool
Reads the contents of an Interface Builder nib file. Prints classes, the hierarchy, objects, connections, and localizable strings.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 5: Hello World
This chapter fulfills the obligation of all self-respecting tutorials to include a Hello World program. The chapter's tutorial shows you how to use the Project Builder application described in Chapter 4, to create a project that builds a Hello World program for Cocoa. Hello World represents the simplest possible working program that does something detectable (like printing a string to the screen). A working Hello World program verifies that your development environment is functioning properly.
The simplest type of Cocoa program is called a Foundation tool. Because this type of program uses only the Foundation framework, it has no graphical user interface (GUI). A Cocoa program that has no GUI is called a tool, to clearly distinguish it from a Cocoa program that does have a GUI, which is called an application. Unlike Cocoa applications that use the Application Kit Framework (detailed in Chapter 1), Foundation tools can be run only from within Project Builder and from the command line.
Foundation tools are a great way to quickly create very powerful command-line applications for use in the Mac OS X BSD environment. A Foundation tool is very similar to a standard C program but, because it links with the Foundation framework, it has access to all the power of the Foundation classes in addition to the standard Objective-C constructs.
In this section you'll be led through the steps necessary to create a very simple foundation tool that prints the string "Hello World!"
Before you can start building applications with Project Builder, you need to launch the application:
  1. Find Project Builder in /Developer/Applications.
  2. Double-click the icon.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating the Project
The simplest type of Cocoa program is called a Foundation tool. Because this type of program uses only the Foundation framework, it has no graphical user interface (GUI). A Cocoa program that has no GUI is called a tool, to clearly distinguish it from a Cocoa program that does have a GUI, which is called an application. Unlike Cocoa applications that use the Application Kit Framework (detailed in Chapter 1), Foundation tools can be run only from within Project Builder and from the command line.
Foundation tools are a great way to quickly create very powerful command-line applications for use in the Mac OS X BSD environment. A Foundation tool is very similar to a standard C program but, because it links with the Foundation framework, it has access to all the power of the Foundation classes in addition to the standard Objective-C constructs.
In this section you'll be led through the steps necessary to create a very simple foundation tool that prints the string "Hello World!"
Before you can start building applications with Project Builder, you need to launch the application:
  1. Find Project Builder in /Developer/Applications.
  2. Double-click the icon.
The first time you start Project Builder, you'll be presented with an Assistant to set up your application preferences:
  1. Click Next on the Assistant's welcome page.
  2. Choose your build products location and click Next. The first page of the Assistant asks where you'd prefer to keep the build products (an executable or library, for example) and intermediate build files (object files, for instance). The default is to keep both in the build directory of the current project, but you can choose whatever directory you wish.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 6: Essential Cocoa Paradigms
In this chapter you will explore a handful of programming topics that represent the fundamental building blocks of a Cocoa application. First, you'll learn how to use Cocoa's collection classes, a set of objects whose purpose is to hold other objects. Next, you'll explore the basics of building graphical user interfaces in Cocoa. You'll learn to use Interface Builder and discover how this powerful tool interacts with Project Builder and the Cocoa frameworks to allow you to very quickly prototype and build applications. Last, you'll delve into the intricacies of object ownership and disposal in Cocoa, ensuring that your applications use resources efficiently.
These topics have been singled out for special attention because they are central to the design of the Cocoa frameworks, and the architectural perspectives involved are likely to be unfamiliar to developers new to the subtleties of object-oriented programming. Exploring these design patterns will help steep you in the mindset of Cocoa's creators, as well as illustrate some of the powerful design approaches available with a language as dynamic as Objective-C. Understanding the principles involved will help you use the Cocoa tools and frameworks more effectively, providing the experience you need to work with them instead of against them.
Several classes in Cocoa's Foundation framework create objects whose purpose is to hold other objects (literally, references to objects); these classes are called collection classes. The two most commonly used collection classes are NSArray and NSDictionary. NSArray stores and retrieves objects in an ordered fashion through zero-based indexing. Dictionaries store and retrieve objects using key-value pairs. These collection classes, shown in Figure 6.1, are extremely useful in Cocoa application development.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Cocoa's Collection Classes
Several classes in Cocoa's Foundation framework create objects whose purpose is to hold other objects (literally, references to objects); these classes are called collection classes. The two most commonly used collection classes are NSArray and NSDictionary. NSArray stores and retrieves objects in an ordered fashion through zero-based indexing. Dictionaries store and retrieve objects using key-value pairs. These collection classes, shown in Figure 6.1, are extremely useful in Cocoa application development.
Figure 6.1: Cocoa collection classes
Collection classes come in two forms, mutable and immutable. The immutable versions of these classes (NSArray and NSDictionary, for example) allow you to add items when the collection is created but no further changes are allowed. The mutable versions (NSMutableArray, NSMutableDictionary) allow you to add and remove objects programmatically after the collection object is created.
All collection objects enable you to access a contained value that satisfies a particular external property. This property, generally referred to as a key, varies according to the organizing scheme enforced by the type of collection. For example, the key for an array is an integer that specifies position within the collection; however, a dictionary—for which the term key has more of a conventional meaning—permits any arbitrary value to act as the key for retrieving a contained value.
In addition to storage and retrieval using keys, much of the power of collection classes lies in their ability to manipulate the objects they contain. The collection classes implement methods for performing a variety of functions on the objects they contain. Not every collection object can perform every function, but in general, collection objects can:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Create Graphical User Interfaces in Cocoa
In this section you'll see how Cocoa and Interface Builder combine to simplify and accelerate the process of constructing applications with a graphical user interface. You'll learn about:
  • Windows. A window is an area on the screen (usually, but not always, rectangular) in which an application displays things such as controls, fields, text, and graphics.
  • Nib files. Nib files are files created by Interface Builder that contain windows as well as other user interface objects.
  • Outlets. Outlets are special instance variables created by Interface Builder that allow objects to send messages to one another.
Finally, you'll apply what you've learned by creating a Cocoa application that displays a window with a single text field containing the current date and time.
A window in Cocoa looks very similar to windows in other user environments such as Microsoft Windows or Mac OS 9. A window can be moved around the screen, and windows can be stacked on top of one another like pieces of paper. A typical Cocoa window has a titlebar, a content area, and several control objects.

Section 6.2.1.1: NSWindow and the window server

Many user interface objects other than the standard window are windows. Menus, pop-up menus, and scrolling lists are primarily windows, as are dialog boxes, alerts, Info windows, and tool palettes, to name a few. In fact, anything drawn on the screen must appear in a window. End users, however, may not recognize or refer to them as "windows."
Two interacting systems create and manage Cocoa windows. On the one hand, a window is created by the window server. The window server is a process that uses the internal window management portion of Quartz (the low-level drawing system) to draw, resize, hide, and move windows using Quartz graphics primitives. As depicted in Figure 6.2, the window server also detects user events (such as mouse clicks) and forwards them to applications.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Controls, Cells, and Formatters
Controls and cells lie behind the appearance and behavior of most user interface objects in Cocoa, including buttons, text fields, sliders, and browsers. Although they are quite different types of objects, they interact closely.
Controls enable users to signal their intentions to an application and thus control what is happening. Cells are rectangular areas embedded within a control. Some controls can hold multiple cells as a way to partition their surfaces into active areas. Cells can draw their own contents either as text or image (and sometimes as both), and they can respond individually to user actions. Figure 6.18 shows the relationship between controls and cells.
Figure 6.18: Controls and cells
Controls act as managers of their cells, telling them when and where to draw and notifying them when a user event (mouse click or keystroke) occurs in their areas. This division of labor, given the relative "weight" of cells and controls, conserves memory and provides a great boost to application performance. For example, a matrix of buttons can be implemented as a single control with many cells, instead of a set of individual controls.
A control does not have to have a cell associated with it, but most user interface objects available on Interface Builder's standard palettes are cell-control combinations. Even a simple button—from Interface Builder or programmatically created—is a control (an NSButton instance) associated with an NSButtonCell. The cells in a control such as a matrix must be the same size, but they can be of different classes. More complex controls, such as table views and browsers, can incorporate various sizes and types of cells. Most controls that use a single cell, such as NSButton, provide convenience methods so you don't usually have to deal with the contained cell directly.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Target/Action
The target/action pattern is part of the mechanism by which user interface controls respond to user actions, enabling users to communicate their intentions to an application. The target/action pattern specifies a one-to-one relationship between two objects; the control (more specifically, the control's cell) and its target. When a user clicks a user interface control, the control sends an action message to the target object as depicted in Figure 6.23.
Figure 6.23: Target/action
The target/action relationship is typically defined using Interface Builder, in which you select a target object for a control, along with the specific action message that will be sent to the target. Target/action relationships can also be set (or modified) while an application is running.
The following steps take you through the process of building a simple example application that uses the target/action pattern. In this example, clicking a button in the main window causes the date and time to be updated in a text field.

Section 6.4.1.1: Create the project and user interface

Since the first example provided detailed instructions on creating projects using Project Builder, this example generally does not repeat those instructions. If you forget how to do a step, refer back to the Nib Files project in Section 6.2 to refresh your recollection.
  1. Start Project Builder, if it is not already running.
  2. Create a new Cocoa application project called TargetAction.
  3. Open the main nib file.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Object Ownership, Retention, and Disposal
The problem of object ownership and disposal is a natural concern in object-oriented programming. When an object is created and passed around among various "consumer" objects in an application, which object is responsible for disposing of it? And when? If the object is not deallocated when it is no longer needed, memory leaks. If the object is deallocated too soon, problems may occur in other objects that assume its existence, and the application may crash.
The Foundation framework introduces a mechanism and a policy that helps to ensure that objects are deallocated when—and only when—they are no longer needed.
The policy is quite simple: you are responsible for disposing of all objects that you own. You own objects that you create, either by allocating or copying them. You also own (or share ownership in) objects that you retain. The flip side of this rule is that you should never release an object that you have not retained or created.
In Cocoa you usually create an object by allocating it (alloc) and then initializing it (init or a variant). For example:
NSArray *myArray = [[NSArray alloc] init];
When an array's init method is invoked, the method implementation initializes its instance variables to default values and completes other startup tasks. Similarly, when an object is deallocated, its dealloc method is invoked, giving it the opportunity to release objects it has created, free allocated memory, and so on.
But now another question arises. If the owner of an object must release the object within its programmatic scope, how can it give that object to other objects? The short answer is: the autorelease method, which marks the receiver for later release, enabling it to live beyond the scope of the owning object so that other objects can use it.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 7: Currency Converter Tutorial
In this chapter you'll build a single window application from beginning to end, giving you an opportunity to deepen your understanding of the Cocoa programming paradigms discussed in Chapter 6. For the first time, you'll see the complete work flow typical of Cocoa application development:
  1. Design the application
  2. Create the project (Project Builder)
  3. Create the interface (Interface Builder)
  4. Define the classes (Interface Builder)
  5. Implement the classes (Project Builder)
  6. Build the project (Project Builder)
  7. Run and test the application
The application you'll build in this chapter is called Currency Converter—a simple utility that converts a dollar amount to an amount in another currency. Currency Converter is an extremely simple application, but there's still a design behind it. This design is based upon the Model-View-Controller (MVC) paradigm, the model behind many designs for object-oriented programs. MVC separates an application into different types of objects, each with specific roles and responsibilities. This design paradigm aids in the development of a maintainable, extensible, and reusable code base, as the Currency Converter example will make clear.
An object-oriented application should be based on a design that identifies the objects of the application and clearly defines their roles and responsibilities. You normally work on a design before you write a line of code. You don't need any fancy tools for designing many applications; a pencil and a pad of paper will do.
MVC proposes three types of objects in an application—model, view, and controller—as illustrated in Figure 7.1. In MVC designs, model objects hold data and define the logic that manipulates that data, view objects represent something visible on the user interface (a window or a button, for example), and controller objects act as a mediator between model objects and view objects.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Design the Currency Converter Application
An object-oriented application should be based on a design that identifies the objects of the application and clearly defines their roles and responsibilities. You normally work on a design before you write a line of code. You don't need any fancy tools for designing many applications; a pencil and a pad of paper will do.
MVC proposes three types of objects in an application—model, view, and controller—as illustrated in Figure 7.1. In MVC designs, model objects hold data and define the logic that manipulates that data, view objects represent something visible on the user interface (a window or a button, for example), and controller objects act as a mediator between model objects and view objects.
Figure 7.1: The separation of model, view, and controller objects in an MVC design
The beauty of MVC is that the controller's central, mediating role frees the model objects from having to know about the state and events of the user interface, and that frees the view objects from having to know about the programmatic interfaces of the model objects.
MVC, strictly observed, is not advisable in all circumstances. Sometimes it's best to combine roles. For instance, in a graphics-intensive application, such as an arcade game, you might have several view objects that merge the roles of view and model. In some applications, especially simple ones, you can combine the roles of controller and model; these objects join the special data structures and logic of model objects with the controller's hooks to the interface.

Section 7.1.1.1: MVC in Currency Converter's design

Currency Converter consists of two custom objects—Converter (model) and ConverterController (controller)—as well as a user interface (view) that is implemented using a collection of ready-made Application Kit objects. The converter object is responsible for computing a currency amount and returning that value. Between the user interface and the converter object is a controller object, ConverterController. ConverterController coordinates the activity between the converter object and the UI objects. These relationships are depicted in Figure 7.2.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Create the Currency Converter Project
Now that you have a design for Currency Converter, it's time to start building the application.
Your first step toward completing the application is to create the Project Builder project.
  1. Start Project Builder.
  2. Choose New Project from the File menu.
  3. In the New Project panel, select the Cocoa Application project type and click the Next button.
  4. Name the application Currency Converter.
  5. If you wish, click Set to select a location to save the project in a specific location of your choice. To use the default location, go on to step 6.
  6. Click Finish.
It's a good idea to have Project Builder index a project once it has been created. During indexing Project Builder stores all symbols of the project (classes, methods, globals, etc.) on disk. This allows Project Builder to access project-wide information quickly.
Note that the version of Project Builder included with the first release of Mac OS X contained a bug causing project indexing to fail unless the project had first been built. If you are working with this release, simply build the project before attempting to create a project index.
To create an index, choose Index Project (Command-Option-I) from the Project menu. Once your project has been indexed, you'll be able to use Project Find to search both your project's code and the system headers for symbols. You'll also be able to access reference documentation directly from Project Find results. Creating an index for a Cocoa project the first time will take a while because Project Builder indexes all of the Cocoa headers as well as the ones in your project.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Create the Currency Converter Interface
Currency Converter's interface is really quite simple, consisting of a few text fields and a button. However, the process of creating it will give you an opportunity to explore some of the object layout tools available in Interface Builder that make it a joy to use.
Begin by creating an application's user interface in Interface Builder.
  1. Locate MainMenu.nib in the Resources group in Project Builder.
  2. Double-click to open it. This will open Interface Builder and bring up the nib file.
A default menu bar and window titled Window will appear when the nib file is open.
In this section you'll change the size of the application's main window to accommodate the UI objects to be added.
  1. Using Figure 7.4 as a guide, make the window smaller by dragging an edge of the bottom-right corner of the window inward.
    Figure 7.4: Currency Converter's main window
    You can resize the window more precisely by using the Size menu of the Window Info window.
  2. Choose Show Info from the Tools menu.
  3. Select Size from the pop-up menu.
  4. In the Content Rect area, select Width/Height from the righthand pop-up menu. In the text fields under the Width/Height menu, type 400 in the width (w) field and 200 in the height (h) field as shown in Figure 7.5.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Define the Classes of Currency Converter
Content preview·