0% found this document useful (0 votes)
12 views81 pages

Cocoa Fundamentals Guide download

The document provides a comprehensive guide to Cocoa, detailing its environment, features, and frameworks for application development on Mac OS X and iOS. It covers object-oriented programming with Objective-C, design patterns, and communication between objects, along with practical examples and code listings. Additionally, it includes links to various related programming resources and ebooks.

Uploaded by

fiyazaxamit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views81 pages

Cocoa Fundamentals Guide download

The document provides a comprehensive guide to Cocoa, detailing its environment, features, and frameworks for application development on Mac OS X and iOS. It covers object-oriented programming with Objective-C, design patterns, and communication between objects, along with practical examples and code listings. Additionally, it includes links to various related programming resources and ebooks.

Uploaded by

fiyazaxamit
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Cocoa Fundamentals Guide download

https://ebookbell.com/product/cocoa-fundamentals-guide-2463146

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Cocoa Fundamentals Guide Coll

https://ebookbell.com/product/cocoa-fundamentals-guide-coll-7177454

Ios 12 Programming Fundamentals With Swift Swift Xcode And Cocoa


Basics 5th Edition Matt Neuburg

https://ebookbell.com/product/ios-12-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-5th-edition-matt-neuburg-22034678

Ios 15 Programming Fundamentals With Swift Swift Xcode And Cocoa


Basics 8th Edition Matt Neuburg

https://ebookbell.com/product/ios-15-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-8th-edition-matt-neuburg-36104646

Ios 9 Programming Fundamentals With Swift Swift Xcode And Cocoa Basics
2nd Edition Matt Neuburg

https://ebookbell.com/product/ios-9-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-2nd-edition-matt-neuburg-5313850
Ios 8 Programming Fundamentals With Swift Swift Xcode And Cocoa Basics
1st Edition Matt Neuburg

https://ebookbell.com/product/ios-8-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-1st-edition-matt-neuburg-5471624

Ios 10 Programming Fundamentals With Swift Swift Xcode And Cocoa


Basics 3rd Edition Matt Neuburg

https://ebookbell.com/product/ios-10-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-3rd-edition-matt-neuburg-5563990

Ios 11 Programming Fundamentals With Swift Swift Xcode And Cocoa


Basics 4th Edition Matt Neuburg

https://ebookbell.com/product/ios-11-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-4th-edition-matt-neuburg-10365296

Ios 13 Programming Fundamentals With Swift Swift Xcode And Cocoa


Basics Sixth Edition Matt Neuburg

https://ebookbell.com/product/ios-13-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-sixth-edition-matt-neuburg-11903566

Ios 14 Programming Fundamentals With Swift Swift Xcode And Cocoa


Basics 7th Edition Matt Neuburg

https://ebookbell.com/product/ios-14-programming-fundamentals-with-
swift-swift-xcode-and-cocoa-basics-7th-edition-matt-neuburg-11950384
Cocoa Fundamentals Guide
General

2010-12-13
Java is a registered trademark of Oracle and/or
Apple Inc. its affiliates.
© 2010 Apple Inc. OpenGL is a registered trademark of Silicon
All rights reserved. Graphics, Inc.
Even though Apple has reviewed this document,
No part of this publication may be reproduced, APPLE MAKES NO WARRANTY OR REPRESENTATION,
stored in a retrieval system, or transmitted, in EITHER EXPRESS OR IMPLIED, WITH RESPECT TO
THIS DOCUMENT, ITS QUALITY, ACCURACY,
any form or by any means, mechanical, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR
electronic, photocopying, recording, or PURPOSE. AS A RESULT, THIS DOCUMENT IS
otherwise, without prior written permission of PROVIDED “AS IS,” AND YOU, THE READER, ARE
ASSUMING THE ENTIRE RISK AS TO ITS QUALITY
Apple Inc., with the following exceptions: Any AND ACCURACY.
person is hereby authorized to store IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT,
documentation on a single computer for INDIRECT, SPECIAL, INCIDENTAL, OR
CONSEQUENTIAL DAMAGES RESULTING FROM ANY
personal use only and to print copies of DEFECT OR INACCURACY IN THIS DOCUMENT, even
documentation for personal use provided that if advised of the possibility of such damages.
the documentation contains Apple’s copyright THE WARRANTY AND REMEDIES SET FORTH ABOVE
notice. ARE EXCLUSIVE AND IN LIEU OF ALL OTHERS, ORAL
OR WRITTEN, EXPRESS OR IMPLIED. No Apple
The Apple logo is a trademark of Apple Inc. dealer, agent, or employee is authorized to make
any modification, extension, or addition to this
No licenses, express or implied, are granted warranty.
with respect to any of the technology described Some states do not allow the exclusion or limitation
of implied warranties or liability for incidental or
in this document. Apple retains all intellectual consequential damages, so the above limitation or
property rights associated with the technology exclusion may not apply to you. This warranty gives
described in this document. This document is you specific legal rights, and you may also have
other rights which vary from state to state.
intended to assist application developers to
develop applications only for Apple-labeled
computers.
Apple Inc.
1 Infinite Loop
Cupertino, CA 95014
408-996-1010

iAd is a service mark of Apple Inc.


Apple, the Apple logo, AppleScript, Aqua,
Bonjour, Carbon, Cocoa, Cocoa Touch, eMac,
Finder, iChat, Instruments, iPhone, iPod, iPod
touch, Mac, Mac OS, Objective-C, Quartz,
QuickTime, Safari, Spotlight, and Xcode are
trademarks of Apple Inc., registered in the
United States and other countries.
iPad and Multi-Touch are trademarks of Apple
Inc.
NeXT and NeXTSTEP are trademarks of NeXT
Software, Inc., registered in the United States
and other countries.
Adobe, Acrobat, and PostScript are trademarks
or registered trademarks of Adobe Systems
Incorporated in the U.S. and/or other countries.
IOS is a trademark or registered trademark of
Cisco in the U.S. and other countries and is used
under license.
Intel and Intel Core are registered trademarks
of Intel Corportation or its subsidiaries in the
United States and other countries.
Contents

Introduction Introduction 11

Organization of This Document 11


See Also 12

Chapter 1 What Is Cocoa? 13

The Cocoa Environment 13


Introducing Cocoa 13
How Cocoa Fits into Mac OS X 14
How Cocoa Fits into iOS 16
Features of a Cocoa Application 18
The Development Environment 21
Platform SDKs 21
Overview of Development Workflows 21
Xcode 22
Interface Builder 24
The iOS Simulator Application 26
Performance Applications and Tools 27
The Cocoa Frameworks 29
Foundation 30
AppKit (Mac OS X) 38
UIKit (iOS) 44
Comparing AppKit and UIKit Classes 49
Core Data 50
Other Frameworks with a Cocoa API 52
A Bit of History 53

Chapter 2 Cocoa Objects 55

A Simple Cocoa Command-Line Tool 55


Object-Oriented Programming with Objective-C 56
The Objective-C Advantage 56
The Dynamism of Objective-C 57
Extensions to the Objective-C Language 58
Using Objective-C 64
The Root Class 66
NSObject 67
Root Class—and Protocol 67
Overview of Root-Class Methods 68
Interface Conventions 69
Instance and Class Methods 70

3
2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CONTENTS

Object Retention and Disposal 70


How the Garbage Collector Works 71
How Memory Management Works 73
Object Creation 77
Allocating an Object 77
Initializing an Object 78
The dealloc and finalize Methods 85
Class Factory Methods 86
Introspection 87
Evaluating Inheritance Relationships 87
Method Implementation and Protocol Conformance 88
Object Comparison 89
Object Mutability 90
Why Mutable and Immutable Object Variants? 90
Programming with Mutable Objects 91
Class Clusters 95
Without Class Clusters: Simple Concept but Complex Interface 95
With Class Clusters: Simple Concept and Simple Interface 96
Creating Instances 96
Class Clusters with Multiple Public Superclasses 96
Creating Subclasses Within a Class Cluster 97
Toll-Free Bridging 102
Creating a Singleton Instance 104

Chapter 3 Adding Behavior to a Cocoa Program 107

Starting Up 107
What Happens in the main Function 107
Using a Cocoa Framework 109
Kinds of Framework Classes 109
Cocoa API Conventions 110
Inheriting from a Cocoa Class 112
When to Override a Method 113
When to Make a Subclass 115
Basic Subclass Design 117
The Form of a Subclass Definition 117
Overriding Superclass Methods 119
Instance Variables 119
Entry and Exit Points 121
Initialize or Decode? 122
Storing and Accessing Properties 123
Key-Value Mechanisms 128
Object Infrastructure 129
Error Handling 130
Resource Management and Other Efficiencies 131
Functions, Constants, and Other C Types 132

4
2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CONTENTS

When the Class Is Public (Mac OS X) 132


Multithreaded Cocoa Programs 133
Multithreading and Multiprocessing Resources 133
Multithreading Guidelines for Cocoa Programs 135
Are the Cocoa Frameworks Thread Safe? 136

Chapter 4 Cocoa Design Patterns 137

What Is a Design Pattern? 137


A Solution to a Problem in a Context 137
An Example: The Command Pattern 138
How Cocoa Adapts Design Patterns 139
Abstract Factory 139
Adapter 140
Chain of Responsibility 141
Command 142
Composite 143
Decorator 145
Facade 147
Iterator 148
Mediator 148
Memento 151
Observer 153
Proxy 154
Receptionist 155
Singleton 158
Template Method 158
The Model-View-Controller Design Pattern 160
Roles and Relationships of MVC Objects 160
Types of Cocoa Controller Objects 162
MVC as a Compound Design Pattern 163
Design Guidelines for MVC Applications 165
Model-View-Controller in Cocoa (Mac OS X) 167
Object Modeling 167
Entities 168
Attributes 168
Relationships 169
Accessing Properties 170

Chapter 5 Communicating with Objects 175

Communication in Object-Oriented Programs 175


Outlets 175
Delegates and Data Sources 176
How Delegation Works 177
The Form of Delegation Messages 178

5
2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CONTENTS

Delegation and the Cocoa Application Frameworks 179


Data Sources 180
Implementing a Delegate for a Custom Class 181
The Target-Action Mechanism 182
The Target 182
The Action 183
Target-Action in the AppKit Framework 183
Target-Action in UIKit 186
Bindings (Mac OS X) 187
How Bindings Work 187
How You Establish Bindings 188
Notifications 190
When and How to Use Notifications 191
The Notification Object 193
Notification Centers 193
Notification Queues 194
Ownership of Delegates, Observers, and Targets 196

Document Revision History 199

6
2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
Figures, Tables, and Listings

Chapter 1 What Is Cocoa? 13

Figure 1-1 Cocoa in the architecture of Mac OS X 15


Figure 1-2 Cocoa in the architecture of iOS 16
Figure 1-3 The TextEdit example project in Xcode 23
Figure 1-4 The TextEdit Document Properties window in Interface Builder 25
Figure 1-5 The Interface Builder connections panel 26
Figure 1-6 The Instruments application 27
Figure 1-7 The Foundation class hierarchy 32
Figure 1-8 AppKit class hierarchy—Objective-C 39
Figure 1-9 UIKit class hierarchy 46
Figure 1-10 Examples of managed object contexts and the persistence stack 52
Figure 1-11 Application Kit class hierarchy in 1988 54
Table 1-1 Major classes of the AppKit and UIKit frameworks 49

Chapter 2 Cocoa Objects 55

Figure 2-1 An object’s isa pointer 57


Figure 2-2 Message terminology 65
Figure 2-3 Reachable and unreachable objects 72
Figure 2-4 The life cycle of an object—simplified view 74
Figure 2-5 Retaining a received object 74
Figure 2-6 Copying a received object 75
Figure 2-7 An autorelease pool 76
Figure 2-8 Initialization up the inheritance chain 82
Figure 2-9 Interactions of secondary and designated initializers 84
Figure 2-10 A simple hierarchy for number classes 95
Figure 2-11 A more complete number class hierarchy 95
Figure 2-12 Class cluster architecture applied to number classes 96
Figure 2-13 An object that embeds a cluster object 100
Table 2-1 Attributes for declared properties 62
Table 2-2 Important Objective-C defined types and literals 66
Table 2-3 Class clusters and their public superclasses 97
Table 2-4 Derived methods and their possible implementations 98
Table 2-5 Data types that can be used interchangeably between Core Foundation and
Foundation 103
Listing 2-1 Output from a simple Cocoa tool 55
Listing 2-2 Cocoa code for the SimpleCocoaTool program 55
Listing 2-3 An example of an initializer 80
Listing 2-4 Secondary initializers 83
Listing 2-5 A typical dealloc method 85
Listing 2-6 A factory method for a singleton instance 86

7
2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
FIGURES, TABLES, AND LISTINGS

Listing 2-7 Using the class and superclass methods 87


Listing 2-8 Using isKindOfClass: 88
Listing 2-9 Using respondsToSelector: 88
Listing 2-10 Using conformsToProtocol: 88
Listing 2-11 Using isEqual: 89
Listing 2-12 Overriding isEqual: 89
Listing 2-13 Returning an immutable copy of a mutable instance variable 93
Listing 2-14 Making a snapshot of a potentially mutable object 94
Listing 2-15 Strict implementation of a singleton 105

Chapter 3 Adding Behavior to a Cocoa Program 107

Figure 3-1 The main event loop in Mac OS X 108


Figure 3-2 Invoking a framework method that invokes an overridden method 113
Figure 3-3 Object composition 116
Figure 3-4 Where to put declarations in the interface file 118
Table 3-1 Lock classes 134
Listing 3-1 The main function for a Cocoa application in Mac OS X 108
Listing 3-2 The basic structure of an interface file 117
Listing 3-3 The basic structure of an implementation file 118
Listing 3-4 Initialization helper method 122
Listing 3-5 Implementing accessors for a scalar instance variable 126
Listing 3-6 Implementing accessors for an object instance variable (garbage collection enabled)
126
Listing 3-7 Implementing accessors for an object instance variable—good technique 126
Listing 3-8 Implementing accessors for an object instance variable—better technique 127
Listing 3-9 Lazy-loading of a resource 131

Chapter 4 Cocoa Design Patterns 137

Figure 4-1 Structure diagram for the Command pattern 138


Figure 4-2 The view hierarchy, visual and structural 144
Figure 4-3 Framework object sending a message to its delegate 146
Figure 4-4 View controllers in UIKit 151
Figure 4-5 Bouncing KVO updates to the main operation queue 156
Figure 4-6 Traditional version of MVC as a compound pattern 164
Figure 4-7 Cocoa version of MVC as a compound design pattern 164
Figure 4-8 Coordinating controller as the owner of a nib file 165
Figure 4-9 Employee management application object diagram 168
Figure 4-10 Employees table view 169
Figure 4-11 Relationships in the employee management application 170
Figure 4-12 Relationship cardinality 170
Figure 4-13 Object graph for the employee management application 172
Figure 4-14 Employees table view showing department name 173
Listing 4-1 Declaring the receptionist class 157
Listing 4-2 The class factory method for creating a receptionist object 157

8
2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
FIGURES, TABLES, AND LISTINGS

Listing 4-3 Handling the KVO notification 157


Listing 4-4 Creating a receptionist object 158

Chapter 5 Communicating with Objects 175

Figure 5-1 The mechanism of delegation 177


Figure 5-2 A more realistic sequence involving a delegate 178
Figure 5-3 How the target-action mechanism works in the control-cell architecture 184
Figure 5-4 Bindings between view, controller, and model objects 188
Figure 5-5 Establishing a binding in Interface Builder 189
Figure 5-6 Posting and broadcasting a notification 191
Figure 5-7 A notification queue and notification center 195
Listing 5-1 Sample delegation methods with return values 178
Listing 5-2 Sample delegation methods returning void 179

9
2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
FIGURES, TABLES, AND LISTINGS

10
2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
INTRODUCTION

Introduction

To a developer new to it, Cocoa might seem like a vast, uncharted new world of technology. The features,
tools, concepts, designs, terminology, programming interfaces, and even programming language of this
development environment may all be unfamiliar. Cocoa Fundamentals Guide eases the initial steps to Cocoa
proficiency. It provides an orientation to the technological landscape that is Cocoa. It introduces its features,
basic concepts, terminology, architectures, and underlying design patterns.

You can build Cocoa applications for two platforms: the Mac OS X operating system and iOS, the operating
system for Multi-Touch devices such as iPhone, iPad, and iPod touch. Cocoa Fundamentals Guide presents
Cocoa-related information for both platforms, integrating the information as much as possible and pointing
out platform differences when necessary. The intent is that, as you become familiar with Cocoa for one
platform, it will become easier to transfer that knowledge to software development for the other platform.

Cocoa Fundamentals Guide is structured to lead gradually to a general understanding of what Cocoa
development is all about. It starts with the most basic information—what Cocoa is in terms of its components
and capabilities—and ends with an examination of its major architectures. Each chapter builds on what was
explained in previous chapters. Each section gives the important details about a subject, yet describes it at
only a high level. A section frequently refers you to another document that offers a more comprehensive
description.

In the set of Cocoa developer documentation, Cocoa Fundamentals Guide is the conceptual entry-point
document. It is prerequisite reading for other essential Cocoa guides, such as Cocoa Drawing Guide, View
Programming Guide, and iOS Application Programming Guide. Cocoa Fundamentals Guide assumes little in
terms of prerequisite reading, but readers should be proficient C programmers and should be familiar with
the capabilities and technologies of the platform they will be developing for. For Mac OS X, you can acquire
this familiarity by reading Mac OS X Technology Overview; for iOS, read iOS Technology Overview.

Organization of This Document

Cocoa Fundamentals Guide has the following chapters:

● “What Is Cocoa?” (page 13) introduces Cocoa from a functional and broadly architectural perspective,
describing its features, frameworks, and development environment.

● “Cocoa Objects” (page 55) explains the advantages and basic use of Objective-C, plus the common
behavior, interface, and life cycle of all Cocoa objects.

● “Adding Behavior to a Cocoa Program” (page 107) describes what it's like to write a program using a
Cocoa framework and explains how to create a subclass.

● “Cocoa Design Patterns” (page 137) describes the Cocoa adaptations of design patterns, especially
Model-View-Controller and object modeling.

● “Communicating with Objects” (page 175) discusses the programming interfaces and mechanisms for
communication between Cocoa objects, including delegation, notification, and bindings.

Organization of This Document 11


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
INTRODUCTION
Introduction

See Also

You can find several excellent third-party introductions to Cocoa in technical book stores. You can use these
books to supplement what you learn in Cocoa Fundamentals Guide. In addition, there are a few other Apple
publications that you should read when starting out as a Cocoa developer:

● The Objective-C Programming Language describes the Objective-C programming language and runtime
environment.

● Model Object Implementation Guide discusses basic issues of subclass design and implementation.

● Cocoa Application Tutorial shows you how to build a simple Cocoa application for Mac OS X using the
Xcode development environment, the Cocoa frameworks, and Objective-C. Your First iOS Application is
a tutorial that guides you through the creation of a simple iOS application, showing you along the way
the basics of the Xcode development environment, Objective-C, and the Cocoa frameworks.

● iOS Application Programming Guide presents information specific to the frameworks used to develop
applications for devices running iOS.

12 See Also
2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1

What Is Cocoa?

Cocoa is an application environment for both the Mac OS X operating system and iOS, the operating system
used on Multi-Touch devices such as iPhone, iPad, and iPod touch. It consists of a suite of object-oriented
software libraries, a runtime system, and an integrated development environment.

This chapter expands on this definition, describing the purpose, capabilities, and components of Cocoa on
both platforms. Reading this functional description of Cocoa is an essential first step for a developer trying
to understand Cocoa.

The Cocoa Environment

Cocoa is a set of object-oriented frameworks that provides a runtime environment for applications running
in Mac OS X and iOS. Cocoa is the preeminent application environment for Mac OS X and the only application
environment for iOS. (Carbon is an alternative environment in Mac OS X, but it is a compatibility framework
with procedural programmatic interfaces intended to support existing Mac OS X code bases.) Most of the
applications you see in Mac OS X and iOS, including Mail and Safari, are Cocoa applications. An integrated
development environment called Xcode supports application development for both platforms. The
combination of this development environment and Cocoa makes it easy to create a well-factored, full-featured
application.

Introducing Cocoa
As with all application environments, Cocoa presents two faces; it has a runtime aspect and a development
aspect. In its runtime aspect, Cocoa applications present the user interface and are tightly integrated with
the other visible components of the operating system; in Mac OS X, these include the Finder, the Dock, and
other applications from all environments.

But it is the development aspect that is the more interesting one to programmers. Cocoa is an integrated
suite of object-oriented software components—classes—that enables you to rapidly create robust, full-featured
Mac OS X and iOS applications. These classes are reusable and adaptable software building blocks; you can
use them as-is or extend them for your specific requirements. Cocoa classes exist for just about every
conceivable development necessity, from user-interface objects to data formatting. Where a development
need hasn’t been anticipated, you can easily create a subclass of an existing class that answers that need.

Cocoa has one of the most distinguished pedigrees of any object-oriented development environment. From
its introduction as NeXTSTEP in 1989 to the present day, it has been continually refined and tested (see “A
Bit of History” (page 53)). Its elegant and powerful design is ideally suited for the rapid development of
software of all kinds, not only applications but command-line tools, plug-ins, and various types of bundles.
Cocoa gives your application much of its behavior and appearance “for free,” freeing up more of your time
to work on those features that are distinctive. (For details on what Cocoa offers, see “Features of a Cocoa
Application” (page 18).)

The Cocoa Environment 13


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

iOS Note: Cocoa for iOS supports only application development and not development of any other kind of
executable.

You can use several programming languages when developing Cocoa software, but the essential, required
language is Objective-C. Objective-C is a superset of ANSI C that has been extended with certain syntactical
and semantic features (derived from Smalltalk) to support object-oriented programming. The few added
conventions are easy to learn and use. Because Objective-C rests on a foundation of ANSI C, you can freely
intermix straight C code with Objective-C code. Moreover, your code can call functions defined in non-Cocoa
programmatic interfaces, such as the BSD library interfaces in /usr/include. You can even mix C++ code
with your Cocoa code and link the compiled code into the same executable.

Mac OS X Note: In Mac OS X, you can also program in Cocoa using scripting bridges such as PyObjC (the
Python–Objective-C bridge) and RubyCocoa (the Ruby–Cocoa bridge). Both bridged languages let you write
Cocoa applications in the respective scripting languages, Python and Ruby. Both of these are interpreted,
interactive, and object-oriented programming languages that make it possible for Python or Ruby objects
to send messages to Objective-C objects as if they were Python or Ruby objects, and also for Objective-C
objects to send messages to Python or Ruby objects. For more information, see Ruby and Python Programming
Topics for Mac OS X.

The most important Cocoa class libraries come packaged in two core frameworks for each platform: Foundation
and AppKit for Mac OS X, and Foundation and UIKit for iOS. As with all frameworks, these contain not only
a dynamically sharable library (or sometimes several versions of libraries required for backward compatibility),
but header files, API documentation, and related resources. The pairing of Foundation with AppKit or UIKit
reflects the division of the Cocoa programmatic interfaces into those classes that are not related to a graphical
user interface and those that are. For each platform, its two core frameworks are essential to any Cocoa
project whose end product is an application. Both platforms additionally support the Core Data framework,
which is as important and useful as the core frameworks.

Mac OS X also ships with several other frameworks that publish Cocoa programmatic interfaces, such as the
WebKit and Address Book frameworks; more Cocoa frameworks will be added to the operating system over
time. See “The Cocoa Frameworks” (page 29) for further information.

How Cocoa Fits into Mac OS X


Architecturally, Mac OS X is a series of software layers going from the foundation of Darwin to the various
application frameworks and the user experience they support. The intervening layers represent the system
software largely (but not entirely) contained in the two major umbrella frameworks, Core Services and
Application Services. A component at one layer generally has dependencies on the layer beneath it. Figure
1-1 situates Cocoa in this architectural setting.

14 The Cocoa Environment


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

Figure 1-1 Cocoa in the architecture of Mac OS X

User Experience

Aqua Dashboard Spotlight Accessibility

Application Frameworks

Carbon Java AppKit Core frameworks

Graphics and Media (Application Services)

Core Animation Core Image Core Video QuickTime

OpenGL Quartz Core Audio

Core Services

Carbon Core Launch Services Core Foundation Foundation

Darwin

For example, the system component that is largely responsible for rendering the Aqua user interface, Quartz
(implemented in the Core Graphics framework), is part of the Application Services layer. And at the base of
the architectural stack is Darwin; everything in Mac OS X, including Cocoa, ultimately depends on Darwin to
function.

In Mac OS X, Cocoa has two core Objective-C frameworks that are essential to application development for
Mac OS X:

● AppKit. AppKit, one of the application frameworks, provides the objects an application displays in its
user interface and defines the structure for application behavior, including event handling and drawing.
For a description of AppKit, see “AppKit (Mac OS X)” (page 38).

● Foundation. This framework, in the Core Services layer, defines the basic behavior of objects, establishes
mechanisms for their management, and provides objects for primitive data types, collections, and
operating-system services. Foundation is essentially an object-oriented version of the Core Foundation
framework; see “Foundation” (page 30) for a discussion of the Foundation framework.

AppKit has close, direct dependences on Foundation, which functionally is in the Core Services layer. If you
look closer, at individual, or groups, of Cocoa classes and at particular frameworks, you begin to see where
Cocoa either has specific dependencies on other parts of Mac OS X or where it exposes underlying technology
with its interfaces. Some major underlying frameworks on which Cocoa depends or which it exposes through
its classes and methods are Core Foundation, Carbon Core, Core Graphics (Quartz), and Launch Services:

● Core Foundation. Many classes of the Foundation framework are based on equivalent Core Foundation
opaque types. This close relationship is what makes “toll-free bridging”—cast-conversion between
compatible Core Foundation and Foundation types—possible. Some of the implementation of Core
Foundation, in turn, is based on the BSD part of the Darwin layer.

● Carbon Core. AppKit and Foundation tap into the Carbon Core framework for some of the system services
it provides. For example, Carbon Core has the File Manager, which Cocoa uses for conversions between
various file-system representations.

The Cocoa Environment 15


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

● Core Graphics. The Cocoa drawing and imaging classes are (quite naturally) closely based on the Core
Graphics framework, which implements Quartz and the window server.

● Launch Services. The NSWorkspace class exposes the underlying capabilities of Launch Services. Cocoa
also uses the application-registration feature of Launch Services to get the icons associated with
applications and documents.

Note: The intent of this architectural overview is not to itemize every relationship that Cocoa has to other
parts of Mac OS X. Instead, it surveys the more interesting ones in order to give you a general idea of the
architectural context of the framework.

Apple has carefully designed Cocoa so that some of its programmatic interfaces give access to the capabilities
of underlying technologies that applications typically need. But if you require some capability that is not
exposed through the programmatic interfaces of Cocoa, or if you need some finer control of what happens
in your application, you may be able to use an underlying framework directly. (A prime example is Core
Graphics; by calling its functions or those of OpenGL, your code can draw more complex and nuanced images
than is possible with the Cocoa drawing methods.) Fortunately, using these lower-level frameworks is not a
problem because the programmatic interfaces of most dependent frameworks are written in standard ANSI
C, of which Objective-C language is a superset.

Further Reading: Mac OS X Technology Overview gives an overview of the frameworks, services, technologies,
and other components of Mac OS X. Apple Human Interface Guidelines specifies how the Aqua human interface
should appear and behave.

How Cocoa Fits into iOS


The application-framework layer of iOS is called Cocoa Touch. Although the iOS infrastructure on which
Cocoa Touch depends is similar to that for Cocoa in Mac OS X, there are some significant differences. Compare
Figure 1-2, which depicts the architectural setting of iOS, to the diagram in Figure 1-1 (page 15). The iOS
diagram also shows the software supporting its platform as a series of layers going from a Core OS foundation
to a set of application frameworks, the most critical (for applications) being the UIKit framework. As in the
Mac OS X diagram, the iOS diagram has middle layers consisting of core-services frameworks and graphics
and media frameworks and libraries. Here also, a component at one layer often has dependencies on the
layer beneath it.

Figure 1-2 Cocoa in the architecture of iOS

Application

UIKit Core Frameworks


Cocoa Touch

Media

Core Services Foundation

Core OS

16 The Cocoa Environment


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

Generally, the system libraries and frameworks of iOS that ultimately support UIKit are a subset of the libraries
and frameworks in Mac OS X. For example, there is no Carbon application environment in iOS, there is no
command-line access (the BSD environment in Darwin), there are no printing frameworks and services, and
QuickTime is absent from the platform. However, because of the nature of the devices supported by iOS,
there are some frameworks, both public and private, that are specific to iOS.

The following summarizes some of the frameworks found at each layer of the iOS stack, starting from the
foundation layer.

● Core OS. This level contains the kernel, the file system, networking infrastructure, security, power
management, and a number of device drivers. It also has the libSystem library, which supports the
POSIX/BSD 4.4/C99 API specifications and includes system-level APIs for many services.

● Core Services. The frameworks in this layer provide core services, such as string manipulation, collection
management, networking, URL utilities, contact management, and preferences. They also provide services
based on hardware features of a device, such as the GPS, compass, accelerometer, and gyroscope.
Examples of frameworks in this layer are Core Location, Core Motion, and System Configuration.

This layer includes both Foundation and Core Foundation, frameworks that provide abstractions for
common data types such as strings and collections. The Core Frameworks layer also contains Core Data,
a framework for object graph management and object persistence.

● Media. The frameworks and services in this layer depend on the Core Services layer and provide graphical
and multimedia services to the Cocoa Touch layer. They include Core Graphics, Core Text, OpenGL ES,
Core Animation, AVFoundation, Core Audio, and video playback.

● Cocoa Touch. The frameworks in this layer directly support applications based in iOS. They include
frameworks such as Game Kit, Map Kit, and iAd.

The Cocoa Touch layer and the Core Services layer each has an Objective-C framework that is especially
important for developing applications for iOS. These are the core Cocoa frameworks in iOS:

● UIKit. This framework provides the objects an application displays in its user interface and defines the
structure for application behavior, including event handling and drawing. For a description of UIKit, see
“UIKit (iOS)” (page 44).

● Foundation. This framework defines the basic behavior of objects, establishes mechanisms for their
management, and provides objects for primitive data types, collections, and operating-system services.
Foundation is essentially an object-oriented version of the Core Foundation framework; see
“Foundation” (page 30) for a discussion of the Foundation framework.

Notes: This document uses “Cocoa” generically when referring to things that are common between the
platforms. When it is necessary to say something specific about Cocoa on a given platform, it uses a phrase
such as “Cocoa in Mac OS X.”

As with Cocoa in Mac OS X, the programmatic interfaces of Cocoa in iOS give your applications access to the
capabilities of underlying technologies. Usually there is a Foundation or UIKit method or function that can
tap into a lower-level framework to do what you want. But, as with Cocoa in Mac OS X, if you require some
capability that is not exposed through a Cocoa API, or if you need some finer control of what happens in
your application, you may choose to use an underlying framework directly. For example, UIKit uses the WebKit
to draw text and publishes some methods for drawing text; however, you may decide to use Core Text to

The Cocoa Environment 17


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

draw text because that gives you the control you need for text layout and font management. Again, using
these lower-level frameworks is not a problem because the programmatic interfaces of most dependent
frameworks are written in standard ANSI C, of which the Objective-C language is a superset.

Further Reading: To learn more about the frameworks, services, and other aspects of the iOS platform, see
iOS Technology Overview.

Features of a Cocoa Application

In Mac OS X it is possible to create a Cocoa application without adding a single line of code. You make a new
Cocoa application project using Xcode and then build the project. That’s it. Of course, this application won’t
do much, or at least much that’s interesting. But this extremely simple application still launches when
double-clicked, displays its icon in the Dock, displays its menus and window (titled “Window”), hides itself
on command, behaves nicely with other running applications, and quits on command. You can move, resize,
minimize, and close the window. You can even print the emptiness contained by the window.

You can do the same with an iOS application. Create a project in Xcode using one of the project templates,
immediately build it, and run it in the iOS Simulator. The application quits when you click the Home button
(or press it on a device). To launch the application, click its icon in Simulator. It may even have additional
behaviors; for example, with an application made from the Utility Application template, the initial view "flips”
to a second view when you click or tap the information (“i”) icon.

Imagine what you could do with a little code.

iOS Note: The features and behavior of an application running in iOS are considerably different from a Mac
OS X application, largely because it runs in a more constrained environment. For discussions of application
capabilities and constraints in iOS, see iOS Application Programming Guide.

In terms of programming effort, Cocoa gives you, the developer, much that is free and much that is low-cost.
Of course, to become a productive Cocoa developer means becoming familiar with possibly new concepts,
design patterns, programming interfaces, and development tools, and this effort is not negligible. But
familiarity yields greater productivity. Programming becomes largely an exercise in assembling the
programmatic components that Cocoa provides along with the custom objects and code that define your
program’s particular logic, then fitting everything together.

What follows is a short list of how Cocoa adds value to an application with only a little (and sometimes no)
effort on your part:

● Basic application framework—Cocoa provides the infrastructure for event-driven behavior and for
management of applications, windows, and (in the case of Mac OS X) workspaces. In most cases, you
won’t have to handle events directly or send any drawing commands to a rendering library.

● User-interface objects—Cocoa offers a rich collection of ready-made objects for your application’s user
interface. Most of these objects are available in the library of Interface Builder, a development application
for creating user interfaces; you simply drag an object from the library onto the surface of your interface,
configure its attributes, and connect it to other objects. (And, of course, you can always instantiate,
configure, and connect these objects programmatically.)

Here is a sampling of Cocoa user-interface objects:

18 Features of a Cocoa Application


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

● Windows

● Text fields

● Image views

● Date pickers

● Sheets and dialogs

● Segmented controls

● Table views

● Progress indicators

● Buttons

● Sliders

● Radio buttons (Mac OS X)

● Color wells (Mac OS X)

● Drawers (Mac OS X)

● Page controls (iOS)

● Navigation bars (iOS)

● Switch controls (iOS)

Cocoa in Mac OS X also features technologies that support user interfaces, including those that promote
accessibility, perform validation, and facilitate the connections between objects in the user interface and
custom objects.

● Drawing and imaging—Cocoa enables efficient drawing of custom views with a framework for locking
graphical focus and marking views (or portions of views) as “dirty.” Cocoa includes programmatic tools
for drawing Bezier paths, performing affine transforms, compositing images, generating PDF content,
and (in Mac OS X) creating various representations of images.

● System interaction—In Mac OS X, Cocoa gives your application ways to interact with (and use the
services of ) the file system, the workspace, and other applications. In iOS, Cocoa lets you pass URLs to
applications to have them handle the referenced resource (for example, email or websites); it also provides
support for managing user interactions with files in the local system and for scheduling local notifications.

● Performance—To enhance the performance of your application, Cocoa provides programmatic support
for concurrency, multithreading, lazy loading of resources, memory management, and run-loop
manipulation.

● Internationalization—Cocoa provides a rich architecture for internationalizing applications, making it


possible for you to support localized resources such as text, images, and even user interfaces. The Cocoa
approach is based on users’ lists of preferred languages and puts localized resources in bundles of the
application. Based on the settings it finds, Cocoa automatically selects the localized resource that best

Features of a Cocoa Application 19


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

matches the user’s preferences. It also provides tools and programmatic interfaces for generating and
accessing localized strings. Moreover, text manipulation in Cocoa is based on Unicode by default, and
is thus an asset for internationalization.

● Text—In Mac OS X, Cocoa provides a sophisticated text system that allows you to do things with text
ranging from the simple (for example, displaying a text view with editable text) to the more complex,
such as controlling kerning and ligatures, spell checking, regular expressions, and embedding images
in text. Although Cocoa in iOS has no native text system (it uses WebKit for string drawing) and its text
capabilities are more limited, it still includes support for spellchecking, regular expressions, and interacting
with the text input system.

● Preferences—The user defaults system is based on a systemwide database in which you can store global
and application-specific preferences. The procedure for specifying application preferences is different
for Mac OS X and iOS.

● Networking—Cocoa also offers programmatic interfaces for communicating with servers using standard
Internet protocols, communicating via sockets, and taking advantage of Bonjour, which lets your
application publish and discover services on an IP network.

In Mac OS X, Cocoa includes a distributed objects architecture that allows one Cocoa process to
communicate with another process on the same computer or on a different one. In iOS, Cocoa supports
the capability for servers to push notifications to devices for applications registered to received such
notifications.

● Printing—Cocoa on both platforms supports printing. Their printing architecture lets you print images,
documents, and other application content along a range of control and sophistication. At the simplest
level, you can print the contents of any view or print an image or PDF document with just a little code.
At a more complicated level, you can define the content and format of printed content, control how a
print job is performed, and do pagination. In Mac OS X, you can add an accessory view to the Print dialog.

● Undo management—You can register user actions that occur with an undo manager, and it will take
care of undoing them (and redoing them) when users choose the appropriate menu items. The manager
maintains undo and redo operations on separate stacks.

● Multimedia—Both platforms programmatically support video and audio. In Mac OS X, Cocoa offers
support for QuickTime video.

● Data exchange—Cocoa simplifies the exchange of data within an application and between applications
using the copy-paste model. In Mac OS X, Cocoa also supports drag-and-drop models and the sharing
of application capabilities through the Services menu.

Cocoa in Mac OS X has a couple of other features:

● Document-based applications—Cocoa specifies an architecture for applications composed of a potentially


unlimited number of documents, with each contained in its own window (a word processor, for example).
Indeed, if you choose the “Document-based application” project type in Xcode, many of the components
of this sort of application are created for you.

● Scripting— Through application scriptability information and a suite of supporting Cocoa classes, you
can make your application scriptable; that is, it can respond to commands emitted by AppleScript scripts.
Applications can also execute scripts or use individual Apple events to send commands to, and receive
data from, other applications. As a result, every scriptable application can supply services to both users
and other applications.

20 Features of a Cocoa Application


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

The Development Environment

You develop Cocoa software primarily by using the two developer applications, Xcode and Interface Builder.
It is possible to develop Cocoa applications without using these applications at all. For example, you could
write code using a text editor such as Emacs, build the application from the command line using makefiles,
and debug the application from the command line using the gdb debugger. But why would you want to
give yourself so much grief?

Note: "Xcode” is sometimes used to refer to the complete suite of development tools and frameworks, and
other times specifically to the application that allows you to manage projects, edit source code, and build
executable code.

The origins of Xcode and Interface Builder coincide with the origins of Cocoa itself, and consequently there
is a high degree of compatibility between tools and frameworks. Together, Xcode and Interface Builder make
it extraordinarily easy to design, manage, build, and debug Cocoa software projects.

When you install the development tools and documentation, you may select the installation location.
Traditionally that location has been /Developer, but it can be anywhere in the file system you wish. To
designate this installation location, the documentation uses <Xcode>. Thus, the development applications
are installed in <Xcode>/Applications.

Platform SDKs
Beginning with Xcode 3.1 and the introduction of iOS, when you create a software project you must choose
a platform SDK. The SDK enables you to build an executable that is targeted for a particular release of Mac
OS X or iOS.

The platform SDK contains everything that is required for developing software for a given platform and
operating-system release. A Mac OS X SDK consists of frameworks, libraries, header files, and system tools.
The SDK for iOS has the same components, but includes a platform-specific compiler and other tools. There
is also a separate SDK for iOS Simulator (see “The iOS Simulator Application” (page 26)). All SDKs include
build settings and project templates appropriate to their platform.

Further reading: For more on platform SDKs, see SDK Compatibility Guide.

Overview of Development Workflows


Application development differs for Mac OS X and iOS, not only in the tools used but in the development
workflow.

In Mac OS X, the typical development workflow is the following:

1. In Xcode, create a project using a template from the Mac OS X SDK.

2. Write code and, using Interface Builder, construct your application’s user interface.

3. Define the targets and executable environment for your project.

The Development Environment 21


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

4. Test and debug the application using the Xcode debugging facilities.

As part of debugging, you can check the system logs in the Console window.

5. Measure application performance using one or more of the available performance tools.

For iOS development, the workflow when developing an application is a bit more complex. Before you can
develop for iOS, you must register as a developer for the platform. Thereafter, building an application that’s
ready to deploy requires that you go through the following steps:

1. Configure the remote device.

This configuration results in the required tools, frameworks, and other components being installed on
the device.

2. In Xcode, create a project using a template from the iOS SDK.

3. Write code, and construct your application’s user interface.

4. Define the targets and executable environment for the project.

5. Build the application (locally).

6. Test and debug the application, either in iOS Simulator or remotely in the device. (If remotely, your
debug executable is downloaded to the device.)

As you debug, you can check the system logs for the device in the Console window.

7. Measure application performance using one or more of the available performance tools.

Further reading: For more on the development workflow in iOS, see iOS Development Guide.

Xcode
Xcode is the engine that powers Apple’s integrated development environment (IDE) for Mac OS X and iOS.
It is also an application that takes care of most project details from inception to deployment. It allows you
to:

● Create and manage projects, including specifying platforms, target requirements, dependencies, and
build configurations.

● Write source code in editors with features such as syntax coloring and automatic indenting.

● Navigate and search through the components of a project, including header files and documentation.

● Build the project.

● Debug the project locally, in iOS Simulator, or remotely, in a graphical source-level debugger.

22 The Development Environment


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

Xcode builds projects from source code written in C, C++, Objective-C, and Objective-C++. It generates
executables of all types supported in Mac OS X, including command-line tools, frameworks, plug-ins, kernel
extensions, bundles, and applications. (For iOS, only application executables are possible.) Xcode permits
almost unlimited customization of build and debugging tools, executable packaging (including information
property lists and localized bundles), build processes (including copy-file, script-file, and other build phases),
and the user interface (including detached and multiview code editors). Xcode also supports several
source-code management systems—namely CVS, Subversion, and Perforce—allowing you to add files to a
repository, commit changes, get updated versions, and compare versions.

Figure 1-3 shows an example of a project in Xcode.

Figure 1-3 The TextEdit example project in Xcode

Xcode is especially suited for Cocoa development. When you create a project, Xcode sets up your initial
development environment using project templates corresponding to Cocoa project types: application,
document-based application, Core Data application, tool, bundle, framework, and others. For compiling
Cocoa software, Xcode gives you several options:

● GCC—The GNU C compiler (gcc).

The Development Environment 23


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

● LLVM-GCC—A configuration where GCC is used as the front end for the LLVM (Low Level Virtual Machine)
compiler. LLVM offers fast optimization times and high-quality code generation.

This option is available only for projects built for Mac OS X v10.6 and later.

● Clang—A front end specifically designed for the LLVM compiler. Clang offers fast compile times and
excellent diagnostics.

This option is available only for projects built for Mac OS X v10.6 and later.

For details about these compiler options, see Xcode Build System Guide.

For debugging software, Xcode offers the GNU source-level debugger (gdb) and the Clang Static Analyzer.
The Clang Static Analyzer consists of a framework for source-code analysis and a standalone tool that finds
bugs in C and Objective-C programs. See http://clang-analyzer.llvm.org/ for more information.

Xcode is well integrated with the other major development application, Interface Builder. See “Interface
Builder” for details.

Further Reading: A Tour of Xcode gives an overview of Xcode and provides links to additional
development-tools documentation.

Interface Builder
The second major development application for Cocoa projects is Interface Builder. As its name suggests,
Interface Builder is a graphical tool for creating user interfaces. Interface Builder has been around almost
since the inception of Cocoa as NeXTSTEP. Not surprisingly, its integration with Cocoa is airtight.

Interface Builder is centered around four main design elements:

● Nib files. A nib file is a file wrapper (an opaque directory) that contains the objects appearing on a user
interface in an archived form. Essentially, the archive is an object graph that contains information about
each object, including its size and location, about the connections between objects, and about proxy
references for custom classes. When you create and save a user interface in Interface Builder, all
information necessary to re-create the interface is stored in the nib file.

Nib files offer a way to easily localize user interfaces. Interface Builder stores a nib file in a localized
directory inside a Cocoa project; when that project is built, the nib file is copied to a corresponding
localized directory in the created bundle.

Interface Builder presents the contents of a nib file in a nib document window (also called a nib file
window). The nib document window gives you access to the important objects in a nib file, especially
top-level objects such as windows, menus, and controller objects that have no parent in their object
graph. (Controller objects mediate between user-interface objects and the model objects that represent
application data; they also provide overall management for an application.)

Figure 1-4 shows a nib file opened in Interface Builder and displayed in a nib document window, along
with supporting windows.

24 The Development Environment


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

Figure 1-4 The TextEdit Document Properties window in Interface Builder

● Object library. The Library window of Interface Builder contains objects that you can place on a user
interface. They range from typical UI objects—for example, windows, controls, menus, text views, and
outline views—to controller objects, custom view objects, and framework-specific objects, such as the
Image Kit browser view. The Library groups the objects by categories and lets you browse through them
and search for specific objects. When an object is dragged from the Library to an interface, Interface
Builder instantiates a default instance of that object. You can resize, configure, and connect the object
to other objects using the inspector.

● Inspector. Interface Builder has the inspector, a window for configuring the objects of a user interface.
The inspector has a number of selectable panes for setting the initial runtime configuration of objects
(although size and some attributes can also be set by direct manipulation). The inspector in Figure 1-4
shows the primary attributes for a text field; note that different collapsible sections of the pane reveal
attributes at various levels of the inheritance hierarchy (text field, control, and view). In addition to
primary attributes and size, the inspector features panes for animation effects, event handlers, and
target-action connections between objects; for nib files in Mac OS X projects, there are additional panes
for AppleScript and bindings.

The Development Environment 25


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

● Connections panel. The connections panel is a context-sensitive display that shows the current outlet
and action connections for a selected object and lets you manage those connections. To get the
connections panel to appear, Control-click the target object. Figure 1-5 shows what the connections
panel looks like.

Figure 1-5 The Interface Builder connections panel

Interface Builder uses blue lines that briefly appear to show the compliance of each positioned object, when
moved or resized, to the Aqua human interface guidelines. This compliance includes recommended size,
alignment, and position relative to other objects on the user interface and to the boundaries of the window.

Interface Builder is tightly integrated with Xcode. It “knows” about the outlets, actions, and bindable properties
of your custom classes. When you add, remove, or modify any of these things, Interface Builder detects those
changes and updates its presentation of them.

Further Reading: For further information on Interface Builder, see Interface Builder User Guide. Also refer to
“Communicating with Objects” (page 175) for overviews of outlets, the target-action mechanism, and the
Cocoa bindings technology.

The iOS Simulator Application


For iOS projects, you can select iOS Simulator as the platform SDK for the project. When you build and run
the project, Xcode runs Simulator, which presents your application as it would appear on the device (iPhone
or iPad) and allows you to manipulate parts of the user interface. You can use Simulator to help you debug
the application prior to loading it onto the device.

You should always perform the final phase of debugging on the device. Simulator does not perfectly simulate
the device. For example, you must use the mouse pointer instead of finger touches, and so manipulations
of the interface requiring multiple fingers are not possible. In addition, Simulator does not use versions of
the OpenGL framework that are specific to iOS, and it uses the Mac OS X versions of the Foundation, Core
Foundation, and CFNetwork frameworks, as well as the Mac OS X version of libSystem.

More importantly, you should not assume that the performance of your application on Simulator is the same
as it would be on the device. Simulator is essentially running your iOS application as a "guest” Mac OS X
application. As such, it has a 4 GB memory partition and swap space available to it as it runs on a processor
that is more powerful than the one on the device.

26 The Development Environment


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

Further reading: For more on iOS Simulator, see iOS Development Guide.

Performance Applications and Tools


Although Xcode and Interface Builder are the major tools you use to develop Cocoa applications, there are
dozens of other tools at your disposal. Many of these tools are performance applications.

Instruments

Instruments is an application introduced in Xcode 3.0 that lets you run multiple performance-testing tools
simultaneously and view the results in a timeline-based graphical presentation. It can show you CPU usage,
disk reads and writes, memory statistics, thread activity, garbage collection, network statistics, directory and
file usage, and other measurements—individually or in different combinations—in the form of graphs tied
to time. This simultaneous presentation of instrumentation data helps you to discover the relationships
between what is being measured. It also displays the specific data behind the graphs.

Further Reading: See the Instruments User Guide for complete information about the Instruments application.

Figure 1-6 The Instruments application

The Development Environment 27


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

Shark

Shark is a performance-analysis application that creates a time-based profile of your program’s execution;
over a given period it traces function calls and graphs memory allocations. You can use Shark to track
information for a single program or for the entire system, which in Mac OS X includes kernel components
such as drivers and kernel extensions. Shark also monitors file-system calls, traces system calls and memory
allocations, performs static analyses of your code, and gathers information about cache misses, page faults,
and other system metrics. Shark supports the analysis of code written in C, Objective-C, C++, and other
languages.

Other Performance Applications (Mac OS X)

Many applications are used in measuring and analyzing aspects of a Mac OS X program’s performance. These
applications are located in <Xcode>/Applications/Performance Tools.

● BigTop graphs performance trends over time, providing a real-time display of memory usage, page
faults, CPU usage, and other data.

● Spin Control automatically samples unresponsive applications. You leave Spin Control running in the
background while you launch and test your applications. If applications become unresponsive to the
point where the spinning cursor appears, Spin Control automatically samples your application to gather
information about what your application was doing during that time.

● MallocDebug shows all currently allocated blocks of memory in your program, organized by the call
stack at the time of allocation. At a glance you can see how much allocated memory your application
consumes, where that memory was allocated from, and which functions allocated large amounts of
memory. MallocDebug can also find allocated memory that is not referenced elsewhere in the program,
thus helping you find leaks and track down exactly where the memory was allocated.

● QuartzDebug is a tool to help you debug how your application displays itself. It is especially useful for
applications that do significant amounts of drawing and imaging. QuartzDebug has several debugging
options, including the following:

● Auto-flush drawing, which flushes the contents of graphics contexts after each drawing operation

● A mode that paints regions of the screen in yellow just before they’re updated

● An option that takes a static snapshot of the systemwide window list, showing the owner of each
window and how much memory each window consumes

For performance analysis, you can also use command-line tools such as:

● top, which shows a periodically sampled set of statistics on currently running processes

● gprof, which produces an execution profile of a program

● fs_usage, which displays file-system access statistics

28 The Development Environment


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

Many other command-line tools for performance analysis and other development tasks are available. Some
are located in /usr/bin and /usr/sbin, and some Apple-developed command-line tools are installed in
<Xcode>/Tools. For many of these tools you can consult their manual page for usage information. (To do
this, either choose Help > Open man page in Xcode or type man followed by the name of the tool in a Terminal
shell.)

Further Reading: For more on the performance tools and applications you can use in Cocoa application
development, as well as information on concepts, techniques, guidelines, and strategy related to performance,
see Performance Overview. Cocoa Performance Guidelines covers the performance guidelines for Cocoa.

The Cocoa Frameworks

What makes a program a Cocoa program? It’s not really the language, because you can use a variety of
languages in Cocoa development. It’s not the development tools, because you could create a Cocoa application
from the command line (although that would be a complex, time-consuming task). No, what all Cocoa
programs have in common—what makes them distinctive—is that they are composed of objects that inherit
ultimately from the root class, NSObject, and that are ultimately based upon the Objective-C runtime. This
statement is also true of all Cocoa frameworks.

Note: The statement about the root class needs to be qualified a bit. First, the Foundation framework supplies
another root class, NSProxy; however, NSProxy is rarely used in Cocoa programming. Second, you could
create your own root class, but this would be a lot of work (entailing the writing of code that interacts with
the Objective-C runtime) and probably not worth your time.

On any system there are many Cocoa frameworks, and Apple and third-party vendors are releasing more
frameworks all the time. Despite this abundance of Cocoa frameworks, two of them stand out on each
platform as core frameworks:

● In Mac OS X: Foundation and AppKit

● In iOS: Foundation and UIKit

The Foundation, AppKit, and UIKit frameworks are essential to Cocoa application development, and all other
frameworks are secondary and elective. You cannot develop a Cocoa application for Mac OS X unless you
link against (and use the classes of ) the AppKit, and you cannot develop a Cocoa application for iOS unless
you link against (and use the classes of ) UIKit. Moreover, you cannot develop Cocoa software of any kind
unless you link against and use the classes of the Foundation framework. (Linking against the right frameworks
in Mac OS X happens automatically when you link against the Cocoa umbrella framework.) Classes, functions,
data types, and constants in Foundation and the AppKit have a prefix of “NS”; classes, functions, data types,
and constants in UIKit have a prefix of “UI”.

The Cocoa Frameworks 29


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

Note: In Mac OS X version 10.5 the Cocoa frameworks were ported to support 64-bit addressing. iOS also
supports 64-bit addressing. As part of this effort, various general changes have been made to the Cocoa API,
most significantly the introduction of the NSInteger and NSUInteger types (replacing int and unsigned
int where appropriate) and the CGFloat type (replacing most instances of float). Most Cocoa applications
have no immediate need to make the transition to 64-bit, but for those that do, porting tools and guidelines
are available. 64-Bit Transition Guide for Cocoa discusses these matters in detail.

The Cocoa frameworks handle many low-level tasks for you. For example, classes that store and manipulate
integer and floating-point values automatically handle the endianness of those values for you.

The following sections survey the features and classes of the three core Cocoa frameworks and briefly describe
some of the secondary frameworks. Because each of these core frameworks has dozens of classes, the
descriptions of the core frameworks categorize classes by their function. Although these categorizations
have a strong logical basis, one can plausibly group classes in other ways.

Foundation
The Foundation framework defines a base layer of classes that can be used for any type of Cocoa program.
The criterion separating the classes in Foundation from those in the AppKit is the user interface. If an object
doesn’t either appear in a user interface or isn’t exclusively used to support a user interface, then its class
belongs in Foundation. You can create Cocoa programs that use Foundation and no other framework;
examples of these are command-line tools and Internet servers.

The Foundation framework was designed with certain goals in mind:

● Define basic object behavior and introduce consistent conventions for such things as memory
management, object mutability, and notifications.

● Support internationalization and localization with (among other things) bundle technology and Unicode
strings.

● Support object persistence.

● Support object distribution.

● Provide some measure of operating-system independence to support portability.

● Provide object wrappers or equivalents for programmatic primitives, such as numeric values, strings,
and collections. It also provides utility classes for accessing underlying system entities and services, such
as ports, threads, and file systems.

Cocoa applications, which by definition link either against the AppKit framework or UIKit framework, invariably
must link against the Foundation framework as well. The class hierarchies share the same root class, NSObject,
and many if not most of the AppKit and UIKit methods and functions have Foundation objects as parameters
or return values. Some Foundation classes may seem designed for applications—NSUndoManager and
NSUserDefaults, to name two—but they are included in Foundation because there can be uses for them
that do not involve a user interface.

30 The Cocoa Frameworks


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

Foundation Paradigms and Policies

Foundation introduces several paradigms and policies to Cocoa programming to ensure consistent behavior
and expectations among the objects of a program in certain situations.:

● Object retention and object disposal. The Objective-C runtime and Foundation give Cocoa programs
two ways to ensure that objects persist when they’re needed and are freed when they are no longer
needed. Garbage collection, which was introduced in Objective-C 2.0, automatically tracks and disposes
of objects that your program no longer needs, thus freeing up memory. Foundation also still offers the
traditional approach of memory management. It institutes a policy of object ownership that specifies
that objects are responsible for releasing other objects that they have created, copied, or explicitly
retained. NSObject (class and protocol) defines methods for retaining and releasing objects. Autorelease
pools (defined in the NSAutoreleasePool class) implement a delayed-release mechanism and enable
Cocoa programs to have a consistent convention for returning objects for which the caller is not
responsible. For more about garbage collection and explicit memory management, see “Object Retention
and Disposal” (page 70).

iOS Note: Garbage collection is not available to applications running in iOS.

● Mutable class variants. Many value and container classes in Foundation have a mutable variant of an
immutable class, with the mutable class always being a subclass of the immutable one. If you need to
dynamically change the encapsulated value or membership of such an object, you create an instance
of the mutable class. Because it inherits from the immutable class, you can pass the mutable instance
in methods that take the immutable type. For more on object mutability, see “Object Mutability” (page
90).

● Class clusters. A class cluster is an abstract class and a set of private concrete subclasses for which the
abstract class acts as an umbrella interface. Depending on the context (particularly the method you use
to create an object), an instance of the appropriate optimized class is returned to you. NSString and
NSMutableString, for example, act as brokers for instances of various private subclasses optimized for
different kinds of storage needs. Over the years the set of concrete classes has changed several times
without breaking applications. For more on class clusters, see “Class Clusters” (page 95).

● Notifications. Notification is a major design pattern in Cocoa. It is based on a broadcast mechanism that
allows objects (called observers) to be kept informed of what another object is doing or is encountering
in the way of user or system events. The object originating the notification can be unaware of the
existence or identity of the observers of the notification. There are several types of notifications:
synchronous, asynchronous, and distributed. The Foundation notification mechanism is implemented
by the NSNotification, NSNotificationCenter, NSNotificationQueue, and
NSDistributedNotificationCenter classes. For more on notifications, see “Notifications” (page
190).

Foundation Classes

The Foundation class hierarchy is rooted in the NSObject class, which (along with the NSObject and
NSCopying protocols) define basic object attributes and behavior. For further information on NSObject
and basic object behavior, see “The Root Class” (page 66).

The remainder of the Foundation framework consists of several related groups of classes as well as a few
individual classes. There are classes representing basic data types such as strings and byte arrays, collection
classes for storing other objects, classes representing system information such as dates, and classes

The Cocoa Frameworks 31


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

representing system entities such as ports, threads, and processes. The class hierarchy charts in Figure 1-7
(for printing purposes, in three parts) depict the logical groups these classes form as well as their inheritance
relationships. Classes in blue-shaded areas are present in both the Mac OS X and iOS versions of Foundation;
classes in gray-shaded areas are present only in the Mac OS X version.

Figure 1-7 The Foundation class hierarchy

Value Objects
NSAffineTransform
NSCalendar
NSCache
NSData NSMutableData NSPurgeableData
NSDate NSCalendarDate
NSDateComponents
NSDecimalNumberHandler
NSLocale
NSNull
NSTimeZone
NSValue NSNumber NSDecimalNumber
NSValueTransformer
NSObject
XML
NSXMLNode NSXMLDocument
NSXMLParser NSXMLDTD
NSXMLDTDNode
NSXMLElement
Strings
NSAttributedString NSMutableAttributedString
NSCharacterSet NSMutableCharacterSet
NSString NSMutableString
NSFormatter NSDateFormatter
NSScanner NSNumberFormatter
NSSortDescriptor
Collections
NSArray NSMutableArray
NSDictionary NSMutableDictionary
NSEnumerator NSDirectoryEnumerator
NSHashTable
NSIndexPath
NSIndexSet NSMutableIndexSet
NSMapTable
NSPointerArray
NSPointerFunctions
NSSet NSMutableSet NSCountedSet
Predicates
NSExpression
NSComparisonPredicate
NSPredicate
NSCompoundPredicate

32 The Cocoa Frameworks


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

Objective-C Foundation Continued

Operating-System Services
NSError
NSHost
NSNetService
NSNetServiceBrowser
NSOrthography
NSProcessInfo
NSRunLoop
NSSpellServer
NSTextCheckingResult
NSTimer
NSUserDefaults File System
NSBundle
NSFileHandle
NSFileManager
NSMetadataItem
NSMetadataQuery
NSMetadataQueryAttributeValueTuple
NSMetadataQueryResultGroup NSInputStream
NSStream NSOutputStream
NSObject
URL
NSCachedURLResponse
NSHTTPCookie
NSHTTPCookieStorage
NSURL
NSURLAuthorizationChallenge
NSURLCache
NSURLConnection
NSURLCredential
NSURLCredentialStorage
NSURLDownload
NSURLProtectionSpace
NSURLProtocol
NSURLRequest NSMutableURLRequest
NSURLResponse NSHTTPURLResponse
Interprocess Communication
NSMachPort
NSPipe
NSMessagePort
NSPort
NSSocketPort
NSPortMessage
NSMachBootstrapServer
NSPortNameServer
NSMessagePortNameServer
NSSocketPortNameServer
Locking/Threading
NSConditionLock
NSDistributedLock
NSLock
NSOperation NSBlockOperation
NSOperationQueue NSInvocationOperation
NSRecursiveLock
NSTask
NSThread

The Cocoa Frameworks 33


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

Objective-C Foundation Continued

Notifications
NSNotification
NSNotificationCenter NSDistributedNotificationCenter
NSNotificationQueue
Archiving and Serialization
NSCoder NSArchiver
NSPropertyListSerialization NSKeyedArchiver
NSKeyedUnarchiver
NSPortCoder
NSUnarchiver
Objective-C Language Services
NSAssertionHandler
NSAutoreleasePool
NSClassDescription
NSException
NSGarbageCollector
NSInvocation
NSMethodSignature
NSUndoManager
NSObject
Scripting
NSScriptClassDescription
NSAppleEventDescriptor
NSCloneCommand
NSCloseCommand
NSAppleEventManager
NSCountCommand
NSAppleScript NSCreateCommand
NSDeleteCommand
NSPositionalSpecifier NSExistsCommand
NSGetCommand
NSScriptCoercionHandler NSMoveCommand
NSQuitCommand
NSScriptCommand NSSetCommand
NSIndexSpecifier
NSScriptCommandDescription NSMiddleSpecifier
NSNameSpecifier
NSScriptExecutionContext NSPropertySpecifier
NSRandomSpecifier
NSScriptObjectSpecifier NSRangeSpecifier
NSRelativeSpecifier
NSScriptSuiteRegistry NSUniqueIDSpecifier
NSWhoseSpecifier
NSScriptWhoseTest
NSLogicalTest
NSSpecifierTest

Distributed Objects
NSConnection
NSDistantObjectRequest
NSDistantObject
NSProxy
NSProtocolChecker

These diagrams logically group the classes of the Foundation framework in categories (with other associations
pointed out). Of particular importance are the classes whose instances are value objects and collections.

Value Objects

Value objects encapsulate values of various primitive types, including strings, numbers (integers and
floating-point values), dates, and even structures and pointers. They mediate access to these values and
manipulate them in suitable ways. When you compare two value objects of the same class type, it is their
encapsulated values that are compared, not their pointer values. Value objects are frequently the attributes
of other objects, including custom objects.

Of course, you may choose to use scalars and other primitive values directly in your program—after all,
Objective-C is a superset of ANSI C—and in many cases using scalars is a reasonable thing to do. But in other
situations, wrapping these values in objects is either advantageous or required. For example, because value
objects are objects, you can, at runtime, find out their class type, determine the messages that can be sent

34 The Cocoa Frameworks


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

to them, and perform other tasks that can be done with objects. The elements of collection objects such as
arrays and dictionaries must be objects. And many if not most methods of the Cocoa frameworks that take
and return values such as strings, numbers, and dates require that these values be encapsulated in objects.
(With string values, in particular, you should always use NSString objects and not C-strings.)

Some classes for value objects have mutable and immutable variants—for example, there are the
NSMutableData and NSData classes. The values encapsulated by immutable objects cannot be modified
after they are created, whereas the values encapsulated by mutable objects can be modified. (“Object
Mutability” (page 90) discusses mutable and immutable objects in detail.)

The following are descriptions of what the more important value objects do:

● Instances of the NSValue class encapsulate a single ANSI C or Objective-C data item—for example, scalar
types such as floating-point values as well as pointers and structures

● The NSNumber class (a subclass of NSValue) instantiates objects that contain numeric values such as
integers, floats, and doubles.

● Instances of the NSData class provides object-oriented storage for streams of bytes (for example, image
data). The class has methods for writing data objects to the file system and reading them back.

● The NSDate class, along with the supporting NSTimeZone, NSCalendar, NSDateComponents, and
NSLocale classes, provide objects that represent times, dates, calendar, and locales. They offer methods
for calculating date and time differences, for displaying dates and times in many formats, and for adjusting
times and dates based on location in the world.

● Objects of the NSString class (commonly referred to as strings) are a type of value object that provides
object-oriented storage for a sequence of Unicode characters. Methods of NSString can convert between
representations of character strings, such as between UTF-8 and a null-terminated array of bytes in a
particular encoding. NSString also offers methods for searching, combining, and comparing strings
and for manipulating file-system paths. Similar to NSData, NSString includes methods for writing
strings to the file system and reading them back.

The NSString class also has a few associated classes. You can use an instance of the NSScanner utility
class to parse numbers and words from an NSString object. NSCharacterSet represents a set of
characters that are used by various NSString and NSScanner methods. Attributed strings, which are
instances of the NSAttributedString class, manage ranges of characters that have attributes such as
font and kerning associated with them.

Formatter objects—that is, objects derived from NSFormatter and its descendent classes—are not themselves
value objects, but they perform an important function related to value objects. They convert value objects
such as NSDate and NSNumber instances to and from specific string representations, which are typically
presented in the user interface.

Collections

Collections are objects that store other objects in a particular ordering scheme for later retrieval. Foundation
defines three major collection classes that are common to both iOS and Mac OS X: NSArray, NSDictionary,
and NSSet. As with many of the value classes, these collection classes have immutable and mutable variants.
For example, once you create an NSArray object that holds a certain number of elements, you cannot add
new elements or remove existing ones; for that purpose you need the NSMutableArray class. (To learn
about mutable and immutable objects, see “Object Mutability” (page 90).)

The Cocoa Frameworks 35


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

Objects of the major collection classes have some common behavioral characteristics and requirements. The
items they contain must be objects, but the objects may be of any type. Collection objects, as with value
objects, are essential components of property lists and, like all objects, can be archived and distributed.
Moreover, collection objects automatically retain—that is, keep a strong reference to—any object they
contain. If you remove an object from a mutable collection, it is released, which results in the object being
freed if no other object claims it.

Note: "Retain,” “release,” and related terms refer to memory-management of objects in Cocoa. To learn about
this important topic, see “Object Retention and Disposal” (page 70).

The collection classes provide methods to access specific objects they contain. In addition, there are special
enumerator objects (instances of NSEnumerator) and language-level support to iterate through collections
and access each element in sequence.

The major collection classes are differentiated by the ordering schemes they use:

● Arrays (NSArray) are ordered collections that use zero-based indexing for accessing the elements of
the collection.

● Dictionaries (NSDictionary) are collections managing pairs of keys and values; the key is an object that
identifies the value, which is also an object. Because of this key-value scheme, the elements in a dictionary
are unordered. Within a dictionary, the keys must be unique. Although they are typically string objects,
keys can be any object that can be copied.

● Sets (NSSet) are similar to arrays, but they provide unordered storage of their elements instead of ordered
storage. In other words, the order of elements in a set is not important. The items in an NSSet object
must be distinct from each other; however, an instance of the NSCountedSet class (a subclass of
NSMutableSet) may include the same object more than once.

In Mac OS X, the Foundation framework includes several additional collection classes. NSMapTable is a
mutable dictionary-like collection class; however, unlike NSDictionary, it can hold pointers as well as objects
and it maintains weak references to its contained objects rather than strong references. NSPointerArray
is an array that can hold pointers and NULL values and can maintain either strong or weak references to
them. The NSHashTable class is modeled after NSSet but it can store pointers to functions and it provides
different options, in particular to support weak relationships in a garbage-collected environment.

For more on collection classes and objects, see Collections Programming Topics.

Other Categories of Foundation Classes

The remaining classes of the Foundation framework fall into various categories, as indicated by the diagram
in Figure 1-7 (page 32). The major categories of classes, shown in Figure 1-7, are described here:

● Operating-system services. Many Foundation classes facilitate access of various lower-level services of
the operating system and, at the same time, insulate you from operating-system idiosyncrasies. For
example, NSProcessInfo lets you query the environment in which an application runs and NSHost
yields the names and addresses of host systems on a network. You can use an NSTimer object to send
a message to another object at specific intervals, and NSRunLoop lets you manage the input sources of
an application or other type of program. NSUserDefaults provides a programmatic interface to a
system database of global (per-host) and per-user default values (preferences).

36 The Cocoa Frameworks


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

● File system and URL. NSFileManager provides a consistent interface for file operations such as
creating, renaming, deleting, and moving files. NSFileHandle permits file operations at a lower
level (for example, seeking within a file). NSBundle finds resources stored in bundles and can
dynamically load some of them (for example, nib files and code). You use NSURL and related
NSURL... classes to represent, access, and manage URL sources of data.

● Concurrency. NSThread lets you create multithreaded programs, and various lock classes offer
mechanisms for controlling access to process resources by competing threads. You can use
NSOperation and NSOperationQueue to perform multiple operations (concurrent or nonconcurrent)
in priority and dependence order. With NSTask, your program can fork off a child process to perform
work and monitor its progress.

● Interprocess communication. Most of the classes in this category represent various kinds of system
ports, sockets, and name servers and are useful in implementing low-level IPC. NSPipe represents
a BSD pipe, a unidirectional communications channel between processes.

iOS Note: The name server classes are not in the iOS version of Foundation.

● Networking. The NSNetService and NSNetServiceBrowser classes support the zero-configuration


networking architecture called Bonjour. Bonjour is a powerful system for publishing and browsing
for services on an IP network.

● Notifications. See the summary of the notification classes in “Foundation Paradigms and Policies” (page
31).

● Archiving and serialization. The classes in this category make object distribution and persistence possible.
NSCoder and its subclasses, along with the NSCoding protocol, represent the data an object contains
in an architecture-independent way by allowing class information to be stored along with the data.
NSKeyedArchiver and NSKeyedUnarchiver offer methods for encoding objects and scalar values
and decoding them in a way that is not dependent on the ordering of encoding messages.

● Objective-C language services. NSException and NSAssertionHandler provide an object-oriented


way of making assertions and handling exceptions in code. An NSInvocation object is a static
representation of an Objective-C message that your program can store and later use to invoke a message
in another object; it is used by the undo manager (NSUndoManager) and by the distributed objects
system. An NSMethodSignature object records the type information of a method and is used in message
forwarding. NSClassDescription is an abstract class for defining and querying the relationships and
properties of a class.

● XML processing. Foundation on both platforms has the NSXMLParser class, which is an object-oriented
implementation of a streaming parser that enables you to process XML data in an event-driven way.

Foundation in Mac OS X includes the NSXML classes (so called because the class names begin with
“NSXML”). Objects of these classes represent an XML document as a hierarchical tree structure. This
approach lets you to query this structure and manipulate its nodes. The NSXML classes support several
XML-related technologies and standards, such as XQuery, XPath, XInclude, XSLT, DTD, and XHTML.

● Predicates and expressions. The predicate classes—NSPredicate, NSCompoundPredicate, and


NSComparisonPredicate—encapsulate the logical conditions to constrain a fetch or filter object.
NSExpression objects represent expressions in a predicate.

The Cocoa Frameworks 37


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

The Foundation framework for iOS has a subset of the classes for Mac OS X. The following categories of
classes are present only in the Mac OS X version of Foundation:

● Spotlight queries. The NSMetadataItem, NSMetadataQuery and related query classes encapsulate
file-system metadata and make it possible to query that metadata.

● Scripting. The classes in this category help to make your program responsive to AppleScript scripts and
Apple event commands.

● Distributed objects. You use the distributed object classes for communication between processes on
the same computer or on different computers on a network. Two of these classes, NSDistantObject
and NSProtocolChecker, have a root class (NSProxy) different from the root class of the rest of Cocoa.

AppKit (Mac OS X)
AppKit is a framework containing all the objects you need to implement your graphical, event-driven user
interface in Mac OS X: windows, dialogs, buttons, menus, scrollers, text fields—the list goes on. AppKit handles
all the details for you as it efficiently draws on the screen, communicates with hardware devices and screen
buffers, clears areas of the screen before drawing, and clips views. The number of classes in AppKit may seem
daunting at first. However, most AppKit classes are support classes that you use indirectly. You also have the
choice at which level you use AppKit:

● Use Interface Builder to create connections from user-interface objects to your application’s controller
objects, which manage the user interface and coordinate the flow of data between the user interface
and internal data structures. For this, you might use off-the-shelf controller objects (for Cocoa bindings)
or you may need to implement one or more custom controller classes—particularly the action and
delegate methods of those classes. For example, you would need to implement a method that is invoked
when the user chooses a menu item (unless it has a default implementation that is acceptable).

● Control the user interface programmatically, which requires more familiarity with AppKit classes and
protocols. For example, allowing the user to drag an icon from one window to another requires some
programming and familiarity with the NSDragging... protocols.

● Implement your own objects by subclassing NSView or other classes. When subclassing NSView, you
write your own drawing methods using graphics functions. Subclassing requires a deeper understanding
of how AppKit works.

Overview of the AppKit Framework

The AppKit framework consists of more than 125 classes and protocols. All classes ultimately inherit from
the Foundation framework’s NSObject class. The diagrams in Figure 1-8 show the inheritance relationships
of the AppKit classes.

38 The Cocoa Frameworks


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

Figure 1-8 AppKit class hierarchy—Objective-C

User Interface
Cocoa Bindings
NSObjectController NSArrayController NSDictionaryController
NSController NSTreeNode NSTreeController
NSUserDefaultsController
NSButtonCell NSMenuItemCell NSPopUpButtonCell
NSFormCell
NSAlert NSActionCell
NSPathCell NSComboBoxCell
NSBrowserCell
NSSegmentedCell NSPathComponentCell
NSCell NSImageCell
NSSliderCell NSSearchFieldCell
NSTextAttachmentCell
NSStepperCell NSSecureTextFieldCell
NSCollectionViewItem
NSTextFieldCell NSTableHeaderCell
NSDockTile
NSEvent NSPanel NSColorPanel
NSMenu NSFontPanel
NSBox
NSMenuItem NSSavePanel NSOpenPanel
NSClipView
NSPredicateEditorRowTemplate
NSCollectionView NSBrowser
NSResponder
NSObject* NSRulerMarker
NSApplication NSControl NSButton NSPopUpButton
NSDrawer NSMenuView NSColorWell
NSRunningApplication
NSWindow NSMovieView NSImageView
NSStatusBar
NSWindowController NSOpenGLView NSMatrix NSForm
NSStatusItem
NSView NSProgressIndicator NSPathControl
NSTabViewItem
NSViewController NSQuickDrawView NSRuleEditor NSPredicateEditor
NSTableColumn
NSRulerView NSScroller
NSToolbar
NSScrollView NSSegmentedControl
NSToolbarItem NSToolbarItemGroup
NSSplitView NSSlider NSOutlineView
NSTouch
NSTabView NSStepper
NSTrackingArea NSComboBox
NSTableHeaderView NSTableView
NSSearchField
NSTextField
NSSecureTextField
Text
NSGlyphInfo NSText NSTextView
NSGlyphGenerator
NSLayoutManager
NSParagraphStyle NSMutableParagraphStyle
NSTextAttachment
NSTextTable
NSTextBlock
NSTextTableBlock
NSTextContainer
NSTextList
NSAttributedString* NSMutableAttributedString* NSTextStorage
NSTextTab
NSTypesetter NSATSTypesetter

Fonts
NSFont
NSFontManager
NSFontDescriptor

*Class defined in the Foundation framework

The Cocoa Frameworks 39


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

Objective-C Application Kit Continued


Graphics
NSAffineTransform
NSAnimationContext
NSBezierPath
NSCursor
NSGradient
NSGraphicsContext
NSImage NSBitmapImageRep
NSImageRep NSCachedImageRep
NSMovie NSCIImageRep
NSOpenGLContext NSCustomImageRep
CAOpenGLLayer** NSOpenGLLayer NSEPSImageRep
NSOpenGLPixelBuffer NSPDFImageRep
NSOpenGLPixelFormat NSPICTImageRep
NSScreen
NSShadow

Color
CIColor
NSColor
NSColorList
NSColorPicker

Document Support
NSDocument NSPersistentDocument
NSObject* NSDocumentController
NSFileWrapper

Printing
NSPageLayout
NSPrinter
NSPrintInfo
NSPrintOperation
NSPrintPanel

Operating System Services


NSHelpManager
NSPasteboard
NSSound
NSSpeechRecognizer
NSSpeechSynthesizer
NSSpellChecker
NSWorkspace

International Character Input Support


NSTextInputContext

Interface Builder Support


NSNib
NSNibControlConnector
NSNibConnector
NSNibOutletConnector

*Class defined in the Foundation framework


**Class defined in the Quartz Core framework.

As you can see, the hierarchy tree of AppKit is broad but fairly shallow; the classes deepest in the hierarchy
are a mere five superclasses away from the root class and most classes are much closer than that. Some of
the major branches in this hierarchy tree are particularly interesting.

At the root of the largest branch in AppKit is the NSResponder class. This class defines the responder chain,
an ordered list of objects that respond to user events. When the user clicks the mouse button or presses a
key, an event is generated and passed up the responder chain in search of an object that can respond to it.
Any object that handles events must inherit from the NSResponder class. The core AppKit
classes—NSApplication, NSWindow, and NSView—inherit from NSResponder.

The second largest branch of classes in AppKit descend from NSCell. The noteworthy thing about this group
of classes is that they roughly mirror the classes that inherit from NSControl, which inherits from NSView.
For its user-interface objects that respond to user actions, AppKit uses an architecture that divides the labor

40 The Cocoa Frameworks


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

between control objects and cell objects. The NSControl and NSCell classes, and their subclasses, define
a common set of user-interface objects such as buttons, sliders, and browsers that the user can manipulate
graphically to control some aspect of your application. Most control objects are associated with one or more
cell objects that implement the details of drawing and handling events. For example, a button comprises
both an NSButton object and an NSButtonCell object.

Controls and cells implement a mechanism that is based on an important design pattern of the AppKit: the
target-action mechanism. A cell can hold information that identifies the message that should be sent to a
particular object when the user clicks (or otherwise acts upon) the cell. When a user manipulates a control
(by, for example, clicking it), the control extracts the required information from its cell and sends an action
message to the target object. Target-action allows you to give meaning to a user action by specifying what
the target object and invoked method should be. You typically use Interface Builder to set these targets and
actions by Control-dragging from the control object to your application or other object. You can also set
targets and actions programmatically.

Another important design pattern–based mechanism of AppKit (and also UIKit) is delegation. Many objects
in a user interface, such as text fields and table views, define a delegate. A delegate is an object that acts on
behalf of, or in coordination with, the delegating object. It is thus able to impart application-specific logic to
the operation of the user interface. For more on delegation, target–action, and other paradigms and
mechanisms of AppKit, see “Communicating with Objects” (page 175). For a discussion of the design patterns
on which these paradigms and mechanisms are based, see “Cocoa Design Patterns” (page 137).

One of the general features of Mac OS X v10.5 and later system versions is resolution independence: The
resolution of the screen is decoupled from the drawing done by code. The system automatically scales content
for rendering on the screen. The AppKit classes support resolution independence in their user-interface
objects. However, for your own applications to take advantage of resolution independence, you might have
to supply images at a higher resolution or make minor adjustments in your drawing code that take the current
scaling factor into account.

The following sections briefly describe some of the capabilities and architectural aspects of the AppKit
framework and its classes and protocols. It groups classes according to the class hierarchy diagrams shown
in Figure 1-8 (page 39).

General User-Interface Classes

For the overall functioning of a user interface, the AppKit provides the following classes:

● The global application object. Every application uses a singleton instance of NSApplication to control
the main event loop, keep track of the application’s windows and menus, distribute events to the
appropriate objects (that is, itself or one of its windows), set up top-level autorelease pools, and receive
notification of application-level events. An NSApplication object has a delegate (an object that you
assign) that is notified when the application starts or terminates, is hidden or activated, should open a
file selected by the user, and so forth. By setting the NSApplication object’s delegate and implementing
the delegate methods, you customize the behavior of your application without having to subclass
NSApplication.

● Windows and views. The window and view classes, NSWindow and NSView, also inherit from
NSResponder, and so are designed to respond to user actions. An NSApplication object maintains a
list of NSWindow objects—one for each window belonging to the application—and each NSWindow
object maintains a hierarchy of NSView objects. The view hierarchy is used for drawing and handling
events within a window. An NSWindow object handles window-level events, distributes other events to
its views, and provides a drawing area for its views. An NSWindow object also has a delegate allowing
you to customize its behavior.

The Cocoa Frameworks 41


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

Beginning with Mac OS X v10.5, the window and view classes of the AppKit support enhanced animation
features.

NSView is the superclass for all objects displayed in a window. All subclasses implement a drawing
method using graphics functions; drawRect: is the primary method you override when creating a new
NSView.

● Controller classes for Cocoa bindings. The abstract NSController class and its concrete subclasses
NSObjectController, NSArrayController, NSDictionaryController, and NSTreeController
are part of the implementation of Cocoa bindings. This technology automatically synchronizes the
application data stored in objects and the presentation of that data in a user interface. See “The
Model-View-Controller Design Pattern” (page 160) for a description of these types of controller objects.

● Panels (dialogs). The NSPanel class is a subclass of NSWindow that you use to display transient, global,
or pressing information. For example, you would use an instance of NSPanel, rather than an instance
of NSWindow, to display error messages or to query the user for a response to remarkable or unusual
circumstances. The AppKit implements some common dialogs for you such as the Save, Open, and Print
dialogs, used to save, open, and print documents. Using these dialogs gives the user a consistent look
and feel across applications for common operations.

● Menus and cursors. The NSMenu, NSMenuItem, and NSCursor classes define the look and behavior of
the menus and cursors that your application displays to the user.

● Grouping and scrolling views. The NSBox, NSScrollView, and NSSplitView classes provide graphic
“accessories” to other view objects or collections of views in windows. With the NSBox class, you can
group elements in windows and draw a border around the entire group. The NSSplitView class lets
you append views vertically or horizontally, apportioning to each view some amount of a common
territory; a sliding control bar lets the user redistribute the territory among views. The NSScrollView
class and its helper class, NSClipView, provide a scrolling mechanism as well as the graphic objects
that let the user initiate and control a scroll. The NSRulerView class allows you to add a ruler and markers
to a scroll view.

● Table views and outline views. The NSTableView class displays data in rows and columns. NSTableView
is ideal for, but not limited to, displaying database records, where rows correspond to each record and
columns contain record attributes. The user can edit individual cells and rearrange the columns. You
control the behavior and content of an NSTableView object by setting its delegate and data source
objects. Outline views (instances of NSOutlineView, a subclass of NSTableView) offer another approach
to displaying tabular data. With the NSBrowser class you can create an object with which users can
display and navigate hierarchical data.

Text and Fonts

The Cocoa text system is based on the Core Text framework, which was introduced in Mac OS X v10.5. The
Core Text framework provides a modern, low-level, high-performance technology for laying out text. If you
use the Cocoa text system, you should rarely have reason to use Core Text directly.

The NSTextField class implements a simple editable text-input field, and the NSTextView class provides
more comprehensive editing features for larger text bodies.

NSTextView, a subclass of the abstract NSText class, defines the interface to the extended text system.
NSTextView supports rich text, attachments (graphics, file, and other), input management and key binding,
and marked text attributes. NSTextView works with the Fonts window and Font menu, rulers and paragraph
styles, the Services facility, and the pasteboard (Clipboard). NSTextView also allows customizing through

42 The Cocoa Frameworks


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

delegation and notifications—you rarely need to subclass NSTextView. You rarely create instances of
NSTextView programmatically either, because objects in the Interface Builder library, such as NSTextField,
NSForm, and NSScrollView, already contain NSTextView objects.

It is also possible to do more powerful and more creative text manipulation (such as displaying text in a
circle) using NSTextStorage, NSLayoutManager, NSTextContainer, and related classes. The Cocoa text
system also supports lists, tables, and noncontiguous selections.

The NSFont and NSFontManager classes encapsulate and manage font families, sizes, and variations. The
NSFont class defines a single object for each distinct font; for efficiency, these objects, which can represent
a lot of data, are shared by all the objects in your application. The NSFontPanel class defines the Fonts
window that’s presented to the user.

Graphics and Colors

The classes NSImage and NSImageRep encapsulate graphics data, allowing you to easily and efficiently
access images stored in files on the disk and displayed on the screen. NSImageRep subclasses each know
how to draw an image from a particular kind of source data. The NSImage class provides multiple
representations of the same image, and it also provides behaviors such as caching. The imaging and drawing
capabilities of Cocoa are integrated with the Core Image framework.

Color is supported by the classes NSColor, NSColorSpace, NSColorPanel, NSColorList, NSColorPicker,


and NSColorWell. NSColor and NSColorSpace support a rich set of color formats and representations,
including custom ones. The other classes are mostly interface classes: They define and present panels and
views that allow the user to select and apply colors. For example, the user can drag colors from the Colors
window to any color well.

The NSGraphicsContext, NSBezierPath, and NSAffineTransform classes help you with vector drawing
and support graphical transformations such as scaling, rotation, and translation.

Printing and Faxing

The NSPrinter, NSPrintPanel, NSPageLayout, and NSPrintInfo classes work together to provide the
means for printing and faxing the information that your application displays in its windows and views. You
can also create a PDF representation of an NSView object.

Document and File-System Support

You can use the NSFileWrapper class to create objects that correspond to files or directories on disk.
NSFileWrapper holds the contents of the file in memory so that it can be displayed, changed, or transmitted
to another application. It also provides an icon for dragging the file or representing it as an attachment. You
can use the NSFileManager class in the Foundation framework to access and enumerate file and directory
contents. The NSOpenPanel and NSSavePanel classes also provide a convenient and familiar user interface
to the file system.

The NSDocumentController, NSDocument, and NSWindowController classes define an architecture for


creating document-based applications. (The NSWindowController class is shown in the User Interface
group of classes in the class hierarchy charts.) Such applications can generate identical window containers
that hold uniquely composed sets of data that can be stored in files. They have built-in or easily acquired
capabilities for saving, opening, reverting, closing, and managing these documents.

The Cocoa Frameworks 43


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

Internationalization and Character Input Support

If an application is to be used in more than one part of the world, its resources may need to be customized,
or localized, for language, country, or cultural region. For example, an application may need to have separate
Japanese, English, French, and German versions of character strings, icons, nib files, or context help. Resource
files specific to a particular language are grouped together in a subdirectory of the bundle directory (the
directories with the .lproj extension). Usually you set up localization resource files using Interface Builder.
See Internationalization Programming Topics for more information on the Cocoa internationalization facilities.

The NSInputServer and NSInputManager classes, along with the NSTextInput protocol, give your
application access to the text input management system. This system interprets keystrokes generated by
various international keyboards and delivers the appropriate text characters or Control-key events to text
view objects. (Typically the text classes deal with these classes and you won’t have to.)

Operating-System Services

The AppKit provides operating-system support for your application through classes that implement the
following features:

● Sharing data with other applications. The NSPasteboard class defines the pasteboard, a repository
for data that’s copied from your application, making this data available to any application that cares to
use it. NSPasteboard implements the familiar cut/copy-and-paste operation.

● Dragging. With very little programming on your part, custom view objects can be dragged and dropped
anywhere. Objects become part of this dragging mechanism by conforming to NSDragging... protocols;
draggable objects conform to the NSDraggingSource protocol, and destination objects (receivers of
a drop) conform to the NSDraggingDestination protocol. The AppKit hides all the details of tracking
the cursor and displaying the dragged image.

● Spell Checking. The NSSpellServer class lets you define a spell-checking service and provide it as a
service to other applications. To connect your application to a spell-checking service, you use the
NSSpellChecker class. The NSIgnoreMisspelledWords and NSChangeSpelling protocols support
the spell-checking mechanism.

Interface Builder Support

The abstract NSNibConnector class and its two concrete subclasses, NSNibControlConnector and
NSNibOutletConnector, represent connections in Interface Builder. NSNibControlConnector manages
an action connection in Interface Builder and NSNibOutletConnector manages an outlet connection.

UIKit (iOS)
The UIKit framework in iOS is the sister framework of the AppKit framework in Mac OS X. Its purpose is
essentially the same: to provide all the classes that an application needs to construct and manage its user
interface. However, there are significant differences in how the frameworks realize this purpose.

44 The Cocoa Frameworks


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

One of the greatest differences is that, in iOS, the objects that appear in the user interface of a Cocoa
application look and behave in a way that is different from the way their counterparts in a Cocoa application
running in Mac OS X look and behave. Some common examples are text views, table views, and buttons. In
addition, the event-handling and drawing models for Cocoa applications on the two platforms are significantly
different. The following sections explain the reasons for these and other differences.

You can add UIKit objects to your application’s user interface in three ways:

● Use the Interface Builder development application to drag windows, views, and other objects from an
object library.

● Create, position, and configure framework objects programmatically.

● Implement custom user-interface objects by subclassing UIView or classes that inherit from UIView.

Overview of UIKit Classes

As with AppKit, the classes of the UIKit framework ultimately inherit from NSObject. Figure 1-9 presents the
classes of the UIKit framework in their inheritance relationship.

The Cocoa Frameworks 45


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

Figure 1-9 UIKit class hierarchy

UIAcceleration

UIAccelerometer

UIAccessibilityElement
UIBarButtonItem
UIBarItem
UITabBarItem
UIBezierPath

UIColor

UIDevice

UIDocumentInteractionController

UIEvent

UIFont UILongPressGestureRecognizer UIWindow

UIGestureRecognizer UIPanGestureRecognizer UILabel

UIImage UIPinchGestureRecognizer UIPickerView

UILocalizedIndexedCollation UIRotationGestureRecognizer UIProgressView

UILocalNotification UISwipeGestureRecognizer UIActivityIndicatorVIew

UIMenuController UITapGestureRecognizer UIImageView

NSObject UIMenuItem UITabBar

UINavigationItem UIToolbar

UINib UINavigationBar

UIPasteboard UITableViewCell

UIPopoverController UISimpleTextPrintFormatter UIActionSheet

UIPrintFormatter UIMarkupTextPrintFormatter UIAlertView


UITableView
UIPrintInfo UIViewPrintFormatter UIScrollView
UITextView
UIPrintInteractionController UISearchBar

UIPrintPageRenderer UIApplication UIWebView

UIPrintPaper UIView UIControl UIButton

UIResponder UIViewController UISplitViewController UIDatePicker

UIScreen UITabBarController UIPageControl

UIScreenMode UITableViewController UISegmentedControl

UISearchDisplayController UINavigationController UITextField

UITextChecker UIImagePickerController UISlider

UITextInputStringTokenizer UIVideoEditorController UISwitch

UITextPosition

UITextRange

UITouch

46 The Cocoa Frameworks


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

As with AppKit, a base responder class is at the root of the largest branch of UIKit classes. UIResponder also
defines the interface and default behavior (if any) for event-handling methods and for the responder chain,
which is a chain of objects that are potential event handlers. When the user scrolls a table view with his or
her finger or types characters in a virtual keyboard, UIKit generates an event and that event is passed up the
responder chain until an object handles it. The corresponding core objects—application (UIApplication),
window (UIWindow), and view (UIView)—all directly or indirectly inherit from UIResponder.

Unlike the AppKit, UIKit does not make use of cells. Controls in UIKit—that is, all objects that inherit from
UIControl—do not require cells to carry out their primary role: sending action messages to a target object.
Yet the way UIKit implements the target-action mechanism is different from the way it is implemented in
AppKit. The UIControl class defines a set of event types for controls; if, for example, you want a button
(UIButton) to send an action message to a target object, you call UIControl methods to associate the
action and target with one or more of the control event types. When one of those events happens, the control
sends the action message.

The UIKit framework makes considerable use of delegation, another design pattern of AppKit. Yet the UIKit
implementation of delegation is different. Instead of using informal protocols, UIKit uses formal protocols
with possibly some protocol methods marked optional.

Note: For a complete description of the target-action mechanism in UIKit and the AppKit, see “The
Target-Action Mechanism” (page 182). To learn more about delegation and protocols, both formal and informal,
see “Delegates and Data Sources” (page 176) and “Protocols” (page 59).

Application Coordination

Each application running in iOS is managed by a singleton application object, and this object has a job that
is almost identical to that for the global NSApplication object. A UIApplication object controls the main
event loop, keeps track of the application’s windows and views, and dispatches incoming events to the
appropriate responder objects.

The UIApplication object also receives notification of system-level and application-level events. Many of
these it passes to its delegate, allowing it to inject application-specific behavior when the application launches
and terminates, to respond to low-memory warnings and changes in time, and to handle other tasks.

Differences in Event and Drawing Models

In Mac OS X, the mouse and keyboard generate most user events. AppKit uses NSEvent objects to encapsulate
these events. In iOS, however, a user’s finger movements on the screen are what originate events. UIKit also
has a class, UIEvent, to represent these events. But finger touches are different in nature from mouse clicks;
two or more touches occurring over a period could form a discrete event—a pinch gesture, for example.
Thus a UIEvent object contains one or more objects representing finger touches (UITouch). The model for
distributing and dispatching events to objects that can handle them on the two platforms is almost identical.
However, to handle an event, an object must take into consideration the sequence of touches specific to
that event.

UIKit also has gesture recognizers, objects that automate the detection of touches as gestures. A gesture
recognizer analyzes a series of touches and, when it recognizes its gesture, sends an action message to a
target. UIKit provides ready-made gesture recognizers for gestures such as tap, swipe, rotate, and pan. You
can also create custom gesture recognizers that detect application-specific gestures.

The Cocoa Frameworks 47


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

The drawing models are similar for AppKit and UIKit. Animation is integrated into the UIKit drawing
implementation. The programmatic support that UIKit directly provides for drawing is a bit more limited
compared to AppKit. The framework offers classes and functions for Bezier paths, PDF generation, and simple
line and rectangle drawing (through functions declared in UIGraphics.h). You use UIColor objects to set
colors in the current graphics context and UIImage objects to represent and encapsulate images. For drawing
of greater sophistication, an application must use the Core Graphics or OpenGL ES framework.

General User-Interface Classes

Objects on an iOS user interface are visibly different than objects on a Mac OS X user interface. Because of
the nature of the device—specifically the smaller screen size and the use of fingers instead of the mouse and
keyboard for input—user-interface objects in iOS must typically be larger (to be an adequate target for
touches) while at the same time make as efficient use of screen real estate as possible. These objects are
sometimes based on visual and tactile analogs of an entirely different sort. As an example, consider the date
picker object, which is instantiated from a class that both the UIKit and AppKit frameworks define. In Mac
OS X, the date picker looks like this:

This style of date picker has a two tiny areas for incrementing date components, and thus is suited to
manipulation by a mouse pointer. Contrast this with the date picker seen in iOS applications:

This style of date picker is more suited for finger touches as an input source; users can swipe a month, day,
or year column to spin it to a new value.

As with AppKit classes, many of UIKit classes fall into functional groups:

● Controls. The subclasses of UIControl instantiate objects that let users communicate their intent to
an application. In addition to the standard button object (UIButton) and slider object (UISlider), there
is a control that simulates off/on switches (UISwitch), a spinning-wheel control for selecting from
multidimensional sets of values (UIPickerView), a control for paging through documents
(UIPageControl), and other controls.

● Modal views. The two classes inheriting from UIModalView are for displaying messages to users either
in the form of “sheets” attached to specific views or windows (UIActionSheet) or as unattached alert
dialogs (UIAlertView). On iPad, an application can uses popover views (UIPopoverController)
instead of action sheets.

● Scroll views. The UIScrollView class enables instances of its subclasses to respond to touches for
scrolling within large views. As users scroll, the scroll view displays transient indicators of position within
the document. The subclasses of UIScrollView implement table views, text views, and web views.

48 The Cocoa Frameworks


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

● Toolbars, navigation bars, split views, and view controllers. The UIViewController class is a base
class for managing a view. A view controller provides methods for creating and observing views, overlaying
views, handling view rotation, and responding to low-memory warnings. UIKit includes concrete subclasses
of UIViewController for managing toolbars, navigation bars, and image pickers.

Applications use both toolbars and navigation bars to manage behavior related to the “main” view on
the screen; typically, toolbars are placed beneath the main view and navigation bars above it. You use
toolbar (UIToolbar) objects to switch between modes or views of an application; you can also use them
to display a set of functions that perform some action related to the current main view. You use navigation
bars (UINavigationBar) to manage sequences of windows or views in an application and, in effect, to
“drill down” a hierarchy of objects defined by the application; the Mail application, for example, uses a
navigation bar to navigate from accounts to mailbox folders and from there to individual email messages.
On iPad, applications can use a UISplitViewController object to present a master-detail interface.

Text

Users can enter text in an iOS application either through a text view (UITextView) or a text field
(UITextField). These classes adopt the UITextInputTraits protocol to specify the appearance and
behavior of the virtual keyboard that is presented when users touch the text-entry object; any subclasses
that enable entry of text should also conform to this protocol. Applications can draw text in views using
UIStringDrawing methods, a category on the NSString class. And with the UIFont class you can specify
the font characteristics of text in all objects that display text, including table cells, navigation bars, and labels.

Applications that do their own text layout and font management can adopt the UITextInput protocol and
use related classes and protocols to communicate with the text input system of iOS.

Comparing AppKit and UIKit Classes


AppKit and UIKit are Cocoa application frameworks that are designed for different platforms, one for Mac
OS X and the other for iOS. Because of this affinity, it is not surprising that many of the classes in each
framework have similar names; in most cases, the prefix (“NS” versus “UI”) is the only name difference. These
similarly named classes fulfill mostly similar roles, but there are differences. These differences can be a matter
of scope, of inheritance, or of design. Generally, UIKit classes have fewer methods than their AppKit
counterparts.

Table 1-1 describes the differences between the major classes in each framework.

Table 1-1 Major classes of the AppKit and UIKit frameworks

Classes Comparison

NSApplication The classes are strikingly similar in their primary roles. They provide a singleton
UIApplication object that sets up the application’s display environment and event loop, distributes
events, and notifies a delegate when application-specific events occur (such as
launch and termination). However, the NSApplication class performs functions
(for example, managing application suspension, reactivation, and hiding) that are
not available to an iOS application.

The Cocoa Frameworks 49


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
CHAPTER 1
What Is Cocoa?

Classes Comparison

NSResponder These classes also have nearly identical roles. They are abstract classes that define
UIResponder an interface for responding to events and managing the responder chain. The main
difference is that the NSResponder event-handling methods are defined for the
mouse and keyboard, whereas the UIResponder methods are defined for the
Multi-Touch event model.

NSWindow The UIWindow class occupies a place in the class hierarchy different from the place
UIWindow NSWindow occupies in AppKit; it is a subclass of UIView, whereas the AppKit class
inherits directly from NSResponder. UIWindow has a much more restricted role in
an application than does NSWindow. It also provides an area for displaying views,
dispatches events to those views, and converts between window and view
coordinates.

NSView These classes are very similar in purpose and in their basic sets of methods. They
UIView allow you to move and resize views, manage the view hierarchy, draw view content,
and convert view coordinates. The design of UIView, however, makes view objects
inherently capable of animation.

NSControl Both classes define a mechanism for objects such as buttons and sliders so that,
UIControl when manipulated, the control object sends an action message to a target object.
The classes implement the target-action mechanism in different ways, largely
because of the difference between event models. See “The Target-Action
Mechanism” (page 182) for information.

NSViewController The role of both of these classes is, as their names suggest, to manage views. How
UIViewController they accomplish this task is different. The management provided by an
NSViewController object is dependent on bindings, which is a technology
supported only in Mac OS X. UIViewController objects are used in the iOS
application model for modal and navigation user interfaces (for example, the views
controlled by navigation bars).

NSTableView NSTableView inherits from NSControl, but UITableView does not inherit from
UITableView UIControl. More importantly, NSTableView objects support multiple columns of
data; UITableView objects display only a single column of data at a time, and thus
function more as lists than presentations of tabular data.

Among the minor classes you can find some differences too. For example, UIKit has the UITextField and
UILabel classes, the former for editable text fields and the latter for noneditable text fields used as labels;
with the NSTextField class you can create both kinds of text fields simply by setting text-field attributes.
Similarly, the NSProgressIndicator class can create objects in styles that correspond to instances of the
UIProgressIndicator and UIProgressBar classes.

Core Data
Core Data is a Cocoa framework that provides an infrastructure for managing object graphs, including support
for persistent storage in a variety of file formats. Object-graph management includes features such as undo
and redo, validation, and ensuring the integrity of object relationships. Object persistence means that Core
Data saves model objects to a persistent store and fetches them when required. The persistent store of a

50 The Cocoa Frameworks


2010-12-13 | © 2010 Apple Inc. All Rights Reserved.
Other documents randomly have
different content
Just then, Angela burst in to say that Major Harewood wanted Felix
to come and see about the new barn, and Felix had sent to ask if
Miss May would come out before the warmth of the short day was
past.
'That's hard,' said Lance, as she went; 'you'll lose the light.'
'Never mind, there will be plenty of time. The pensive face is what I
want. It can be rather fine.'
'Rather!' in an indignant tone.
Lance slept in the third room in the corridor, opening into Clement's,
as Clement's did into Felix's—an arrangement convenient in the
earlier stage of his convalescence, and enabling Clement still to take
care that his fire never was let out.
'I say, Clem,' he said, from his bed, the next morning, 'you haven't
such a thing as a spare razor—mine were left at Marshlands.'
'No, I haven't.'
'I wish you would see if Felix has.'
'Are you mad, to want to begin shaving now?'
'Not at all. It had better be done before it gets thicker, and I have to
go out.'
The application brought Felix in, demanding, 'Are you gone crazy,
Lance?'
'I thought I might as well titivate myself for the tithe dinner this
evening.'
'You need not trouble yourself about that. You'll not dine with us;
and if you did, the farmers would excuse you. I thought you were
only too glad of an apology for cultivating that furze brake.'
'One may as well be fit to be seen.'
'Exactly my sentiments,' said Felix; 'but you must submit for the
present. If you say any more, I shall lock up all my razors from the
raving lunatic.'
'Yes,' added Clement. 'Would you like an axe at the same time, to
cut off your head?'
Lance subsided; and Felix walked back to his room, and smiled to
the risk of his own cheeks over his shaving, as he muttered, 'Tithe
dinner, quotha?'
The tithe and rent dinner were always combined soon after
Christmas, and the Squire and Vicar had agreed that it was best not
to make it a wholesale entertainment at the Rood, but to have a
civilized party in the Priory, bringing the guests into the drawing-
room afterwards. The numbers of superior tenants were not
sufficient to make this unmanageable, and the compliment was
appreciated. One or two elderly men might have preferred devouring
the value of their tithe at the inn, and enjoying subsequent tobacco
and spirits, but most liked the being treated as gentlemen; and the
evening was always an odd mixture of boredom, amusement, and
gratification.
The audit occupied most of the day, and the dinner was at the
primitive hour of six, the ladies of the house appearing thereat.
Gertrude, who was worked up to think it capital fun, was warned to
deck herself in her best; and she rejoiced that Ethel had enforced
preparations for possible gaieties, so that she could appear in a pink
silk, presented to her for Mrs. Rivers's last public occasion, and a
wreath of clematis.
Her splendours were not thrown away, for the Squire met her on the
stairs, and exclaimed, 'That's right, I'm grateful to you;' and next
moment she saw Mrs. Harewood uncloaking, and revealing the black
velvet her husband always urged on her, and a set of pearls that had
not seen the light since the last old aunt retired into old-
maidenhood. The Vale Leston opinion was that Mrs. Harewood was
the finest woman to look at who had existed since her great-
grandmother, Lady Geraldine.
Lance was in the drawing-room when the ladies came in after dinner,
shaking out their plumes and relating their experiences. Angela had
talked hunting with a young farmer whom she wanted to allure into
the choir, though Cherry doubted whether Clement would like to
have him there. Cherry had given Mr. Hodnet an account of the
Caergwent wedding, in which Penbeacon had had so much share,
and had received a lament over Mr. Harewood's absence that winter.
'He was a gentleman that was strong in the pulpit.'
'That's his tincture of Irish eloquence, and the go that he has in
him!' said Angela.
'I believe the poor people do prefer his preaching to Clement's,' said
Wilmet.
'On the variety principle, I believe,' said Cherry.
'Of which they never get enough,' said Angela.
'After all,' said Cherry, 'inherent poetry does tell more than one
guesses upon an audience.'
'Ah, ha!' said Lance; 'I've got a novelty in that line for you.'
'From Will? You don't mean that you've been revelling in the second
post?'
'Ay! Some one fetched it from Ewmouth, just as your knives and
forks began to clatter. I was just thinking what notes predominated,
when in came this budget from San Remo. It is satisfactory to hear
that while my Lord and my Lady think it the dullest place in the
world, our two lovers find it simply delicious.'
'Is that the subject of the poem?'
'It might be,' said Gertrude.
'Only it would be hard on my Lord and my Lady,' said Angel.
'The question would be,' said Cherry, 'how long it takes to be so
used to one another that localities cease to be indifferent.'
'How long does it take, Wilmet?' saucily asked Angela.
Wilmet did not choose to answer; and Stella's voice quietly
mentioned how Lizzie Bruce and her lover broke off their
engagement after being shut up together for a whole wet Sunday.
'How very lucky for them!' said Gertrude.
'They agreed it would be impossible to spend life together,' said
Cherry. 'But what is the poem, Lance?'
'The Song of the Electric Wires.'
'Nonsense!'
'They do sing,' said Gertrude. 'I have often wished one could make
something of those Æolian-harp sounds.'
'Have you?' said Lance. 'I've tried ever so often to get them on the
violin. I'll show you.'
It was the first time he had spoken of touching his instrument; but
Wilmet intercepted Stella, who was going as a matter of course to
fetch it, by saying the sound would make the farmers expect a
dance.
'So much the better,' said Angela. 'One waltz with Harry Palting, and
my victory would be complete.'
'It seems,' proceeded Lance, 'that poor Bobbie held herself ready to
start off with Bill in case I had been worse; and when the telegraph
relieved their minds, the reaction showed itself in these verses.'
'Which Bobbie was there to secure,' added Cherry. 'I wonder how
many of his get lost for want of her to copy them out, and make him
polish them.'
'When a man hasn't a spark of vanity he misses a very good working
machine,' said Lance.
'Spurring machine, you mean,' said Gertrude.
'Let me have them, Lance; you can't read them,' interposed Cherry.
Strange as was the subject, there was a wild airy grace about the
lines, by turns joyous and pathetic, and really going well to the fitful
music of the winds upon the wires. Lance went up to the piano, and
struck a note or two; and that wonderful power he possessed over
the instrument brought the very expression, if not the sound, and
made Gertrude exclaim with delight, 'Oh! do make a song of it with
a piano accompaniment; I am sure you can.'
'If you tell me I can,' said Lance, flushing and smiling, though
perhaps aware of more technical difficulty than she knew; but the
opening of the dining-room door, and the warm greeting of his
brother's tenants, broke off his promise.
He worked so hard and so merrily the next day in preparing the
Christmas-tree for the schools, in spite—foolish fellow!—of warnings,
chills, and catches of breath, that at the moment of projection, he
was quite overcome by the throng, noise and glare, and forced to
beat a hasty retreat to the drawing-room, whither Miss Bridget
Hepburn soon pursued him.
Finding him for the first time on the sofa, looking worn out she
viewed his assurances that he was really much better as a
melancholy delusion, and warned him against being beguiled by
false hopes out of that blessed frame of mind. John Harewood,
divining what she was about, presently came in to the rescue; not
that he could remove her, for she was burning to communicate a
semi-confidential piece of information, namely, the intended
marriage of Mrs. Fulbert Underwood to Mr. Smiles, whose sickly wife
had been dead about a year. The other two sisters were
communicating the same intelligence to any one they could catch in
anything like privacy all the evening. It was not at all unsatisfactory
intelligence, for on the strength of Clement's appointment having
caused his resignation, Mr. Smiles had expected him to supply all his
most pressing needs, from educating his son to paying for his wife's
funeral. The worst of it was that it was hardly credible that Mrs.
Fulbert would be so foolish as to bestow her handsome jointure
upon him and his seven children; but as he had just taken a curacy
in a popular watering-place, there might be attractions; and at any
rate, Clement would be exempted from finding funds for his move.
Lance could not help feeling that if to be weary of everything and
indifferent to the future were a blessed frame, he had certainly lost
it, and it made the subsequent night of pain and distress all the less
endurable, as well as the captivity to bed and blisters that ensued;
nor was it till Sunday evening that he could return to the painting-
room, where all the family collected as they dropped in one by one
from Evensong and the subsequent choir-practice, and stood and
lounged about in the Sunday gossip, deaf to all to the manner born.
Felix came in last, having been looking at his letters, for he never
had time to do more than glance at a few of the more interesting in
the morning.
'It is true,' he said quietly.
'What, about Mrs. Fulbert? Has she written?'
'Yes; a great deal about the love she always had for Mr. Smiles's
dear little family, and an entreaty to me not to deprive her of the
three hundred a year that she was to forfeit by remarriage.'
'Was she? cried Bernard. 'How jolly!'
'So it seems, though I had forgotten it. She keeps all the settlement,
of course.'
'I remember about it,' said Clement. 'Her husband begged his father
to do something for her; and he detested her so, poor woman, that
it went very much against the grain with him, and by way of some
solace, he must have made this charge on the estate contingent on
her remaining a widow.'
'You'll never go on with it, Felix!' exclaimed Angela.
'I hope it will not break off the match,' added Cherry. 'There are
some people whom one would willingly bribe to keep out of one's
way.'
'They do it knowingly?' said Gertrude.
'I imagine so; Smiles managed to know most things.'
'Ay!' said Angela. 'But you see he went on precedents. He knew
what Alice Lamb had effected, and had some personal experience of
this Vicar!'
'Felix! you are not going to be so absurd!' expostulated Bernard.
'Why, it would keep a hunter!'
'Or a curate,' said Angela.
'Still more amusing to you, Angel,' retorted Bernard.
'But, Felix, do promise me you'll do nothing foolish. For my personal
satisfaction,' pleaded Angela.
'That is a promise no one can be warranted in giving, Angela.'
'He's afraid of himself!' cried Angela. 'She has only to get him into a
corner—like Alice.'
'Then it is well I am going away to-morrow.'
'Very unreasonable,' muttered Lance.
'What, to be so soft—I think it is indeed! I don't care for the money,
but how those critters will triumph!'
'He never said they would have it,' said Cherry.
'Oh! if he is only teasing.—What are you going to do, Felix?'
'I do not know. I must look at the terms of the will.'
Gertrude looked triumphantly at Angela, as much as to say, 'Could
you not trust his common sense and justice?'
But Felix put a stop to the conversation by asking Lance whether the
usual Sunday evening hymns would be too much for him.
'Not at all,' he said, 'provided Angela would sing nothing she had not
studied;' and then finding Gertrude took this as a hint, he was
dreadfully distressed, and nearly implied that dissonance from her
was better than harmony from any one else. She, on the other hand,
was as ever, greatly impressed with the sweetness of Felix's voice,
and refused, as they went down to supper, to believe that Lance's
could be better.
'I do not know that it is in what you heard to-night,' said Cherry; 'but
Lance had some notes that none of them could come near, except—'
and there she paused, thinking of the voice that still at times she
longed for with inexpressible longing.
Gertrude was full of pity, though disappointed to find that Mr.
Underwood was going away so early that he bade her good-bye as
well as good-night, in spite of her protestation that she should be up
to see him off, and binding over Stella, who was always the morning
star of early travellers, to wake her in time for his 6.30 breakfast.
It was not far from that time when Felix, coming into Lance's room,
was struck with his refreshed and brightened look even at this his
worst time, a sort of indefinable look of hope and recovery.
'You have had a good night?'
'Yes; I slept till just now. I believe this last bout of mustard has done
me a power of good. The tightness is gone as it never went before.'
'That's the best news I've heard yet.'
'Better than Mrs. Fulbert?'
'Oh, I was coming to that. I have looked at the abstract of the will
this morning, and I don't feel myself in the least bound to continue
the annuity. Then I have been going over things this week; and what
with the falling in of the Blackstone lease, and the winding up of the
Rectory business, I shall be likely to get into smooth waters sooner
than I expected. So if you can hold on to the end of the year, I will
then, if all goes right, do whichever you please—give up the concern
at Bexley to you, or let you have an allowance to enable you to go
on with your music.'
'Have I been grumbling?' said Lance.
'Can't one see a thing without its being grumbled at one? It is a hard
life, yours, Lancey. I did not understand how hard till I took this
taste of it, and I am heartily grieved at having let you go on under it
till you broke down. I must try some other plan for you when you
can go back.'
'No, no; don't upset Mrs. Frog. Summer will be coming, and I prefer
her to Mrs. Lamb any day. Give her my love, and tell her I'm
mending. Not that I see any sense in your going,' he added, but
somehow a little less freely than usual.
'You want to see Lamb's report of the speeches at the sessions? Any
commands?'
'Yes; I want some music-paper, and my portfolio of violin music. If
you are sending any books, it might come at once. And tell Ellis he
had better not attempt that anthem from the Creation next Sunday,
unless Speers is come home to take the tenor.'
'I might do that.'
'You don't mean to stay over Sunday?'
'It is of no use to be always running backwards and forwards; I like
a Sunday at the old place now and then,' said Felix. 'Good-bye,
Lancey; let me find you twice yourself when I come back!'
'I could not thank the old Giant,' said Lance, when Cherry looked in
on him; 'but will you tell him, I feel as if he had taken out the
stopper that bunged me up from everything. Only it is absurd of him
to go into banishment just when this place is so uncommonly
pleasant?'
Cherry thought she could guess, and that it was not so entirely
distrust of Mr. Lamb's capacity as it was convenient for the family to
suppose. And after all, Lance was protesting from dutiful habit of
unselfishness, but it may be doubted whether he really was quite as
sorry as usual to part with his brother.
The early rising to see him off had been effected; but his absence
did not disturb the good spirits of the party. Lance was gaining
ground quickly, and resumed more of the ordinary family habits
every day—sustaining his spirits the better when left behind on their
all going out, because Gertrude May did not unite with Angela in
abusing the weather for not bringing a skateable frost, and far less
in running wild after a sight of the hunt. Nay, she decidedly snubbed
that great handsome idle fellow Bernard for abusing Felix and the
Fates for not mounting him, and sat soberly at home at her music
lesson, when he and Angela went off upon the chestnut and Ratton,
to see the meet and bemoan themselves. Gertrude had been slow to
exhibit her music before the Underwoods, and had good-humouredly
justified Angela's exaggerated excruciation, owning that she had
never had any teaching worthy of the name. Lance had diffidently
offered a few hints, and they were not accepted as Angela was wont
to receive his criticisms; so they developed into instruction, delightful
to both, even though much of it consisted in unlearning!
And when the little niece had rallied, and Dr. May fetched his
daughter home, Lance did not flag, but was once more the bright
Lance of former days, and spent his time between Pursuivant work
and labour over some musical achievement, dividing himself
between a blotted score, his violin, and piano, using by preference
Theodore as a critic, with Stella to interpret his gestures.

CHAPTER XLII.

A HALCYON DAY.

'They had been much together; and one for


ever bears
A name upon the loyal heart, and in the daily
prayers;
The other but remembers, when the pleasant
hours are past,
That something has been sending them so
sweetly and so fast.'
S M.
On Whit-Monday forenoon 'Mr. Underwood' was announced in the
drawing-room at Stoneborough, and Gertrude May's face, which had
at first clouded at the pre-prandial intrusion of any visitor, brightened
at the name, but lost a little eagerness when the entering visitor
proved himself to be only Lancelot, shaven now all but his
moustache, and with an air of entirely recovered health, justifying
his declaration that he had no desire to see the Doctor
professionally, and had been quite well ever since his return to
Bexley at Easter. He was now on his way to keep his holiday at
home, but had made a deviation 'to show that I have tried to obey
you,' he said, proffering to Gertrude a roll of music, the stiff paper
cover beautifully and delicately adorned with a daisy border, with
pen-and-ink etchings in the corners illustrating the receipt of
telegrams for weal or woe, and the first bars were made to resemble
the wires and posts, the notes, the birds perched thereon, the whole
being of course William Harewood's poem set to music. So beautiful
and elaborate was the finish, that Gertrude was startled and
confused; the meaning flashed on her, and the sudden recoil roused
the contradictoriness of her nature. The earnest look abashed and
frightened her, and with a sort of anger she coldly said, 'Very pretty,
very nicely got up.'
'I think it may suit your voice,' said Lance wistfully.
'Thank you' (more nervously, and therefore more coldly), 'we will
order some copies.'
Lance, after a moment's pleading gaze, dropped his eyes, coloured,
and stammered, 'Not that.'
Ethel came to the rescue with praise of the etching, but this availed
little; Gertrude spoke not a word, and Lance, though making some
kind of reply, clearly did not know what he was saying, and presently
took leave, in spite of Ethel's entreaties that he would stay to the
early dinner, and to see her father. He made answer in a bewildered
voice about not meaning—and getting home; shook hands, and was
gone.
'That was not gracious, Daisy,' said Ethel.
'I'm sure I didn't want it,' said the spoilt child.
'You need not have hurt him.'
No answer but scarlet colouring.
About half-past three he was at the Priory, just as the whole party
and Charles Audley besides were standing on the lawn, with rugs
and cloaks betokening boating intentions. His first impulse was to
shrink away like some wounded animal, but he had been spied, and
was eagerly hailed—'O Lance! just in time! Here's the four-oar
coming out! Clem and Angel want to go up the river to Tranquillity
Bridge, and we are taking them.'
Lance would have done anything rather than betray his wound, so
he took his place in the boat, and tried to shake himself into the
present; but Felix thought he looked tired, and would not let him
take an oar against the stream. Then it occurred to Cherry to ask
whether he had had anything to eat. No, he believed not; but he
was resolute that he wanted nothing, not even a draught of cider,
which Angela mischievously recommended as they passed the 'Hook
and Line,' a little tea-garden public-house, a favourite Sunday resort
of Ewmouth idlers, and a great scandal and grievance to the Vicar,
but secured, like other abuses, by a lease. A boat, belonging no
doubt to some holiday-makers, was moored at the steps; but as it
was the day of a great Maying at East Ewmouth, most observers of
'tide time' were likely to be there absorbed.
Angela amused herself with wild proposals to Charlie Audley to
repair thither in disguise together, talking nonsense that greatly
annoyed Clement, and was far from pleasing Felix or Cherry; but she
was in so reckless and defiant a mood, that they could only hope
that she might work it off at the oar. Her arms were strong as well
as long, and rowing was a pastime she loved, having been franked
as an A B S ever since she had taken lessons at a swimming-bath.
The day was delicious, with clouds chasing one another so as to
make fleeting lights and shadows on Penbeacon and the hills
beyond; the clear brown water sparkling in ripples or lying in deep
pools, shadowed by the woods that came down to the bank in the
early green of spring, flowering may, mountain ash, and wreaths of
blushing eglantine overhanging the margin, or where the space was
open, revealing meadows all one golden sheet of buttercups, while
the fringe of the stream was the feathery bogbean and the golden
broom, mixed with tall sword leaves of the flag and the reed.
Shaded at length by a picturesque high-backed one-arched bridge,
the boat waited while Clement and Angela went on their cottage
visiting.
Charlie did not, as Cherry expected, invite Lance to promenade the
bank with a cigar, but applied himself to helping Stella in collecting a
grand nosegay of every sort of flower and grass within reach. The
others remained in the boat: Lance leaning over the gunwale
dreamily watching the ripples, apparently half asleep, lulled by the
monotonously sweet humming of Theodore, and the songs of the
birds in the woods; Cherry was sketching, and Felix rested musingly.
'Tranquillity Bridge,' he said. 'I always fancy it must have been
named by some pious builder imbued with the spirit of the Pilgrim's
Progress.'
'An unconscious poet,' said Cherry.
'Yes. Such a tranquil rest, amid such perfect peace and loveliness,
without one discordant element, is one of the choicest boons of life.'
Lance swallowed a sigh; and Cherry answered, 'The very movements
and sounds are all peace, though full of life.'
For a gold-billed moorhen was swimming among its little ones at the
margin of the reeds at the bend of the river, and a sapphire
kingfisher darted across the arch.
'Halcyon days,' said Felix.
'Oh no! Halcyon days precede storms.'
'Maybe they give strength for them. Times like these are surely
foretastes of perfect bliss.'
'How does that prepare for storms?'
'Not only by calming nerves and spirits, but by giving some
experience of the joy beyond—ay, and sense of love and confidence
in Him who has made all so exquisite for our delight.'
It seemed to come from his heart, drawn forth by the grateful
enjoyment of that sweet Whitsun hour.
Cherry held up her finger as a ring-dove began to coo from the
thicket, making fit answer to one thus resting in the Feast of the
Comforter; Theodore cooed in return, and the bird seemed to be
replying. Even the tumult of pain and grief in Lance's breast was
soothed by the spirit of the words and scene, while he felt the
contrast, like an abyss, between himself and the others.
But when the rest of the party came gaily back with talk and
laughter, inaction had become intolerable to him. He wanted to take
Angela's oar, but she would not hear of giving it up, and Felix
resigned his, while Cherry owned that she preferred having him at
the helm when going down the river.
Theodore, with a shout, held out his hands for Stella's flowers, and
she gave the whole into his hands, Charlie for a moment looking
disappointed; but as the twins sat together, and the little fellow drew
out the flowers singly and dropped them into his sister's lap, while
she whispered their names, it was evidently perfect joy to both.
Some, such as the bright spires of broom, he greeted with a snatch
of nursery song, though otherwise the pair were scarcely audible as
long as the nosegay lasted, and that was for a long time; but when
Stella had made it up again, only leaving the broom to him, he
returned to his usual hum, and this time with the tune of 'The strain
upraise,' which had been practised that morning for Trinity Sunday,
and which met the sound of the bells ringing for Evensong.
'That's rather too much!' exclaimed Angela. 'We shall be taken for
some of the pious, a singing of hymns.—Come, Tedo.'
'No, no,' said Felix, 'I'll not have him interfered with.' And he
hummed the tune.
'That's always the way when Baby goes out with us,' muttered
Angela, audaciously singing out at the top of her clear soprano—
'Six o'clock is striking,
Mother, may I go out?
My young man is waiting,
To take me all about.

First he gives me apples,


Then he gives me pears;
Then he gives me sixpence,
To take me round the fairs;'
thus effectually silencing both the others, the one from sense of
discord, the other from serious displeasure. At that moment,
shooting from behind the bend of the river where stood the Hook
and Line, came the other boat. Excited probably by the song, the
young men in it shouted 'Come on! Who'll be first! We'll take a
couple of your sweethearts aboard, to make fair play! We'll have
your nightingale!'
'Next he gives me bacon
And eggs to fry in the pan,
And no one there to eat them
But me and my young man.'
sung they lustily, as on they came, as fast as the current, assisted by
twelve vigorous arms, could carry them.
A few strokes would have gained the garden landing-place, but the
pursuers' velocity was reckless. One moment as they passed the
eddy of the junction of the Leston, and the end of the four-oar
swung round into the middle of the river, there was a shock, a shriek
of many voices; and just as John and Wilmet Harewood were
crossing the lawn to return to their own cottage, they beheld both
boats upset, and fifteen persons struggling in the midstream.
Even as the collision took place, Felix had seized Theodore, and after
both had been drawn down for a second, rose again, making
vigorous strokes with one arm for the bank, reaching that of the
churchyard, where it was built up high and steep; but with one of
the violent efforts of a supreme moment, he grasped a branch of the
overhanging willow tree, swung himself up by one arm till his feet
had a hold, and he could launch himself partly over the iron rail, and
deposit his burthen on the grass, when climbing over, he reached
down and dragged up Geraldine from the arm of Clement, who had
closely followed him.
By that time both the other sisters were safe; Charles Audley,
thoroughly at home in the water, had directed himself more skilfully,
holding Stella by her shoulder, to the garden landing-place, further
off, but of easier access. Indeed, she had not lost the power of
helping herself, when Wilmet's arms clasped her on the steps; and
only a few moments later, Angela, who had kept herself afloat, was
likewise landed, with very little aid from Charles.
Lance's rescue was harder. He could not swim at all, sank twice, and
rose the second time a little way down the stream, where John
Harewood grappled him and brought him to the steps, helpless and
at first unconscious. Of the other boat's crew, two reached the bank
alone, another had saved his fellow, a fifth clung to his oar, and was
guided ashore by Clement, a sixth was drawn out insensible by
young Audley; the last was still missing, and John, Charles, one of
the other lads, and old Tripp, were all striving to find and rescue
him. Four figures lay insensible, three more were struggling back to
life—the servants rushing down; Wilmet, supporting Lance in his
gasping efforts, took the command. 'Angel, Stella—don't wait, back
to the house. Change instantly.—Amelia, go with them, give them
something hot, never mind what, and put Miss Underwood to bed.—
Yes, Clement, carry her to her room; and you—don't do anything
else till you have changed—Felix, we'll take Tedo to the laundry; it is
hot, and flannels can be warmed sooner.—Golightly, you and Martha
take this one.—You two the other.—Follow Mr. Underwood—Yes, dear
Lancey, you are better. They are all safe. Shall I help you up? That's
right. Lean on, my dear, more than that; don't be afraid, I'm strong
enough; there, you get on very well.'
Before they had made many steps, a shout proclaimed that the last
sufferer had been found; and while he was carried between his
friend and Tripp, Wilmet hastily insisted that her husband should
hurry home and change his clothes before doing anything else, and
relinquishing Lance to Charlie to be helped up-stairs, hastened to the
scene of action in the laundry, where the four lifeless figures were
stretched on the ironing tables. The other three young men were
sent to be between blankets till their clothes could be dried; and
Felix, after having laid down his unconscious burthen, lingered for a
moment, till Wilmet ordered him off to change his dripping clothes,
when he obeyed without a word.
Clement, half-dressed, was finding garments for Charlie, and
insisting that bed was the place for Lance, when there was a sudden
call at his door, and as he opened it Angela stood before him,
exclaiming, 'Come this instant!' and as he followed her flying steps,
he beheld Felix on the stairs, sitting propped against the balusters,
holding a handkerchief to his mouth covered with blood. He had
been standing, supporting himself against the post at the bottom,
when Angela had first found him, and had so far helped him up; but
the effort had evidently been agonizing, and increased the bleeding
so much, that she had tried to place him safely, and hurried for aid.
He could do nothing for himself, but Charles Audley coming to their
assistance, they brought him to his room door, where Angela, crying,
'Ice! ice is the thing!' dashed away to the offices, where she heard
voices.
'Miss Angela, you mus'n't come here.'
'Quick, Martha, the key of the ice-house.'
'Hice-ouse! bless you, Miss Hangela, 'tis 'ot as is wanted.'
'It is ice for the bleeding. It's a blood-vessel! It is Felix. I must have
the key.'
But Martha, always despising Angela, and now all the more with her
hair streaming below her waist, simply did not hear, and hurried
away with her flannels. Angela rushed after her, but only heard, 'You
can't come here.'
As she was raising her voice for a more peremptory cry, she saw
John Harewood returning. He understood in a moment, made
entrance, obtained the key, and while she fetched the ice, he hurried
to the scene of the most pressing and grievous need.
By the time she brought the ice, the drenched clothes had been
removed, and Felix was in bed, and the remedy she had obtained
did at last check the flow of blood, but there was not only
exhaustion but evidently very severe pain. 'Where?' He put his hand
to his right side; and at that moment, to their infinite relief, they
found among them Dr. Thomas May, the professor, who—on his way
home from a visit to his friend the chemist—had been met in the
village and brought to their aid even before Page, who was out on
his rounds.
The verdict of the first moment was that the hæmorrhage was not
from the lungs, and indeed the patient showed no difficulty in
speaking after the first faintness. Had he felt the hurt on throwing
himself over the rail? He thought so, but could not recollect; it only
became disabling when he tried to go up-stairs, and that brought
the bleeding—'but Theodore! Pray go to Theodore!'
There was no withstanding his anxiety, only the Professor directed
the unsuccessful endeavour to make the posture easier, and ordered
fomentations as the only present alleviation, except perfect stillness.
No judgment could be formed as yet, and he therefore gratified the
ardent desire faintly breathed forth, while the great drops of pain
stood on the brow. 'Please, see Geraldine! And when Theodore
comes round, bring him here! Clem, see it is so; he will be pacified
in sight of me.'
Clement promised, and made it plain that it would be better for
both; and then he took the young doctor first to Geraldine, who,
once in bed, could not leave it without assistance, and was chained
there in terrible anxiety, with Stella as her messenger; but her agony
of suspense was her chief ailment, and after saying all he
conscientiously could to soothe her, Dr. Tom was guided to the
laundry, where he vanished.
Long, long was news watched for from thence. Even those who went
in quest of hot water learnt nothing, till at last Charlie heard that
one of the young men was reviving, and presently he was carried up
to the spare room.
Another quarter, another half-hour dragged by. Felix renewed his
entreaty for Theodore's presence, but messenger after messenger
returned not. First John went and came back no more, then Clement
was called for and never returned, and Felix became so restless
under the impression that Wilmet would choose to put the child to
bed unhappy in Sibby's room, that Lance could only carry down his
mandate to the contrary. Then when the next access of watching
and anxiety was visibly increasing the suffering and danger, Angela
left Stella in charge, and went herself to represent that the dire
suspense must be relieved before it did further harm.
The ear was in a state of agonized tension, and caught a sound.
'Open the door, Stella. Hark!'
She obeyed. There were voices; Wilmet's—Clement's. 'You go!'—'He
will bear it best from you!' they said.
She heard no more, for Felix had started up on his elbow, and the
blood had again rushed to his lips. She called for help. All were
about him, there was no checking it, for seconds—for minutes. His
face was deathly, his hands cold. Clement, holding him on his breast,
whispering prayers, felt him more prone and feeble every instant; all
believed that a life was ebbing away far more precious than the little
feeble spark so easily quenched.
When a respite came, it was with a hand on the pulse, and with an
anxious face, that the doctor durst signify to them that this was
relief—not the end as yet; but as Clement laid the head back the
furrows of pain had cleared, the brow had smoothed, the breath
came without the stifled groans, the position was less constrained,
and when Angela ventured to say, 'He looks more comfortable,'
there was an air of assent and rest, the worst of the pain was
evidently relieved for the time.
Stella stole away with the tidings to poor Geraldine, whom she found
sitting up in bed, trembling so that the whole framework shook, and
totally unable to move from it, without the appliances that assisted
her lameness. Before long, Wilmet was able to attend to a
representation of her condition, and could bring her wonted
remedies, and what was even better, her strong soft arms to enfold
the little frail quivering frame, and her sweet, steady, full voice to
assure her that Felix was undoubtedly better, and not suffering near
so much.
And when Cherry was quieted, and Wilmet would have returned, the
little handmaid said, in an imploring voice, 'Where is dear Tedo?
mayn't I go to him now?'
'My dear child!' exclaimed Wilmet, in pitying consternation, 'then you
don't know?'
Cherry saw what was implied! How else could the helpless darling
have been left by all!
'It is so?' she said.
Wilmet bent her head.
Stella gave a kind of moan.
'Yes,' Wilmet said, 'It is nearly three hours since. The Professor said
there might be hope for two. One young man is getting better at
last, Page is with him. We went on trying—John says for two hours
and a quarter, and Sibby is going on still; but there is no hope now;
and when I heard about Felix—Stella, dear child, where are you
going?'
'Mayn't I help Sibby?' The voice was so plaintively imploring, the
eyes looked so mournfully earnest out of the loose damp mass of
dark brown hair, that it seemed cruel to answer, 'Stella, dear dear
little one, indeed you must not, you can't go there.'
Instinctive obedience recalled her; but still she pleaded, 'He must
get better! He was such a little moment under water! I think he is
afraid to open his eyes because I am not there, nor Brother. Do let
me try! I'm sure he would know me.'
'Stella, sweet, indeed I would let you if I could; but you can't go to
the laundry, there are strange men about, and they are making up a
bed for young Light; he can't be moved. The hope is quite gone, my
dear, it was such a feeble little tender life.'
'And there could have been no pain or fright,' said Cherry.
But she broke off, as poor little Stella collapsed with her face
between her hands, sitting on the floor, lost in her hair, not speaking,
only a great stifling smothering sob heaving up, as if the oppression
of her first grief were crushing, nay strangling her.
Wilmet knelt down to gather her into her motherly arms, and
whisper comfort, but this was not what she wanted; she somehow
slid away, stood up, and said, 'Please, may I go into my own room? I
want to be by myself.'
'To your room and your bed, my dear,' said Wilmet. 'I am going to
send you both some tea.'
Cherry only had visits from the maids, with tea that refreshed her,
but from which Stella in the inner room turned away. The summer
twilight had passed into night before a long black figure looked in.
'Asleep, Cherry?'
'Oh no, Clem! I knew you would come.'
'I am sorry not to have come before, but there has been so much to
do.'
'And he?'
'Tom May thinks his pulse stronger, and was struck by the look of
rally about his face when we came back after supper.'
'Who is there now?'
'Wilmet and the Professor. May will let no one sit up who has been in
the water. I care the less because with my door open it is almost like
being in the same room.'
'But he is better?'
'Not in pain,' said Clement; 'and May thinks that there are no ribs
broken, though there is a great bruise. Much may be only violent
sprain, and it may be only some unimportant vessel that has given
way; but he is too weak and tender yet for anything like
examination. However, as long as the bleeding does not return, he is
gaining every hour.'
'It was that dreadful scramble up the bank!'
'That quite accounts for it; and he must have twisted himself as he
threw himself over the rail. No one could have done it in cold blood,
even without dear Baby's weight.'
'And after that he pulled me up! Clem, it was you that saved me,
and yet I could not thank you if—O Clem!' She laid her head on his
shoulder, struggling with horror at the bare notion of life without
Felix.
He was very sorry for her. He had always loved her the best of his
sisters, yet he felt himself so inadequate to fill to her the place of
their eldest, or even of the lost Edgar.
'My poor Cherry!' he said, stroking her damp hair; 'but thus far God
has been very gracious to us, and we will take hope, and trust Him.
Think how much worse it might have been. So many in danger, and
the only one taken so surely gone home!'
'Ah! I can only think how happy we were so short a moment before.
He said halcyon weather came to bear us through storms; but oh! it
makes it worse.'
'You will not think so when you see our little one's countenance,
sealed with his Alleluia! The vacancy is gone, and there is a
wonderful depth in his face, as if his Ephphatha had come to the
guileless lips. Sibby and I have been dressing him in his surplice, and
laying him under the Cross in the Oratory with his broom blossoms
in his hand. Sibby says he was still clutching them when Felix gave
him to her. Poor Sibby, she says her heart stood still then; but she
would not cease from trying to restore him till long after we all knew
it was vain; and when I made her desist, for the sake of young
Light, who must be kept quiet, I thought she would have broken her
heart; but at last she seemed to feel the soothing awe of the dear
little face; and she has got her beads, and means to keep her vigil
over him all night.'
'Does he know?'
'Wilmet fancies not, and is on the watch for his asking; but I am
sure he understood, when I thought he was fast going, and told him
Theodore was "safe home." I am sure it made it easier;' and as
Cherry winced and shuddered, he added, 'This calmness after the
suspense was over was really what did him most good. He is better
every hour, and no one else of ourselves at all the worse except
Lance. When the alarm was over, we found him shivering violently,
and hardly able to hold up his head. I believe that his danger was
the greatest of all, and that he could not have been saved but for
John; the stream was carrying him down against the bridge.'
'O Clem! help me to be thankful! But is not one poor fellow really
taken?'
'Yes, a fine young lad about Bernard's age. He had been under water
so long, that we never had much hope; but the whole frame seemed
so made for vigour, that Page thought there might be a return, and
went on with Krishnu's help for four hours—nor did Sibby leave off
till after that. They were a party of clerks and shopmen from Spiers
and Hart's. The four who are gone home are very subdued and
grateful. The father of one came out in a fly and took them all back,
though I thought it rather a risk for the lad who had been so long
insensible.'
'Then there is one in the red-room.'
'He had had some blow, and was too much done up to move; but
Page says he will be all right to-morrow. I am more afraid for the
one in the laundry, and have got Kerenhappuch to sit up with him.
The poor boy who is lying by our dear child was a clerk of Hart's;
Audley was going to see about sending to his people. He went off in
his skiff a couple of hours ago.'
'There's eleven o'clock! O Clem, I ought not to keep you from
resting.'
'This is rest, Cherry.'
'Only leave me something to rest on.'
'What shall I say to you?'
'What you like. There are matches.'
'I need not read.'
And he murmured over her Psalm, Collect, thanksgiving, and prayer,
half quoted, half from his own heart, and then stood to give her his
blessing of peace, and his kiss, which left her hushed, softened,
comforted, attuned to meet whatever might be coming.
Again he was at her door in early morning, with tidings of
reassurance. Felix had spent a quiet night, without recurrence of
bleeding, and though too feeble almost for speech, and unable to
make the least movement without pain, he had so far surmounted
the first danger, that Professor May meant to go away on the return
of the carriage he had sent home at night, and, unless telegraphed
for, would not come again till Thursday, only enforcing absolute
quiescence though not forbidding speech. Clement had seen a great
improvement in looks, and Wilmet had consented to lie down on her
husband's coming to take charge of the patient.
'And Lance?'
'He is getting up to come to Church, though he has had a bad night,
and he looks anything but fit for it. He says he must come even if he
has to go back to his bed.'
'Surely it is too great a risk.'
'So I told him, but he declares he has caught no cold, and that it is
all headache and feverishness, which fresh air will relieve. I don't
know, but I can't withhold him.'
'Whit-Tuesday! I had forgotten. Sunday seems to have been ages
ago!'
'And how are you, Cherry? Did you sleep?'
'In a sort of way; I am quite well, if only any one would come and
help me to get up! I can't bear lying here any longer. Do try to send
me one of the maids. I can't disturb that poor little dear; she is
asleep at last. Take my heart with you, Clement! After all, it is a
sacrifice of thanksgiving this morning.'
Clement was wont to gather his small daily congregation in the Lady
Chapel, where never since the family migration had the early Holy-
day Celebration been so scantily attended. It was in unison with the
many beyond that he made his Commemoration, his oblation, his
intense intercession, in the dewy light of the early summer morning,
his apparently low yet really powerful deep-pitched voice sounding
far down the aisles and among the pillars in the nave.
The blessing echoed beyond the enclosing screen, and presently
Lance rose from his knees and moved slowly westwards. If for a
space he had felt some of the joy of holy comfort on the renewal of
the sacrifice of self, soul and body, love and hope, before the Lord of
life and death, yet he was more conscious of the oppression of the
sickly odour of the drooping greenery and faded flowers that hung
trailing on column and poppy-head, and which compelled him to
leave the Church, though every step down the nave seemed to
increase the load of sorrow, anxiety, and wounded affection,
beneath which head and heart had burnt and throbbed the long
night through. If he had reinforced patience and resolution, he could
not yet feel the benefit.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy