100% found this document useful (3 votes)
144 views

(Ebook) Cocoa Programming for Mac OS X by Aaron Hillegass, Adam Preble ISBN 9780321774088, 0321774086 instant download

The document is a comprehensive guide to Cocoa programming for Mac OS X, authored by Aaron Hillegass and Adam Preble. It covers various topics including Objective-C, memory management, user interface design, and advanced features like Core Data and concurrency. The book is aimed at developers looking to create applications for Mac and includes practical examples and challenges to enhance learning.

Uploaded by

quinonsideni69
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
100% found this document useful (3 votes)
144 views

(Ebook) Cocoa Programming for Mac OS X by Aaron Hillegass, Adam Preble ISBN 9780321774088, 0321774086 instant download

The document is a comprehensive guide to Cocoa programming for Mac OS X, authored by Aaron Hillegass and Adam Preble. It covers various topics including Objective-C, memory management, user interface design, and advanced features like Core Data and concurrency. The book is aimed at developers looking to create applications for Mac and includes practical examples and challenges to enhance learning.

Uploaded by

quinonsideni69
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/ 50

(Ebook) Cocoa Programming for Mac OS X by Aaron

Hillegass, Adam Preble ISBN 9780321774088,


0321774086 download

https://ebooknice.com/product/cocoa-programming-for-mac-
os-x-2580832

Explore and download more ebooks at ebooknice.com


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

(Ebook) Cocoa programming for Mac OS X by Aaron Hillegass ISBN


9780321213143, 0321213149

https://ebooknice.com/product/cocoa-programming-for-mac-os-x-2485756

(Ebook) Cocoa(R) Programming for Mac(R) OS X by Aaron Pablo Hillegass


ISBN 9780321503619, 9780321562739, 0321503619, 0321562739

https://ebooknice.com/product/cocoa-r-programming-for-mac-r-
os-x-1365394

(Ebook) Cocoa Programming for OS X: The Big Nerd Ranch Guide, 5/e by
Chandler, Nate;Hillegass, Aaron;Preble, Adam ISBN 9780123456786,
9780134076959, 9780134077130, 0123456789, 0134076958, 013407713X

https://ebooknice.com/product/cocoa-programming-for-os-x-the-big-nerd-
ranch-guide-5-e-11367408

(Ebook) Cocoa programming for Mac OS X for dummies by Erick Tejkowski


ISBN 9780470432891, 9780470477908, 0470432896, 0470477903

https://ebooknice.com/product/cocoa-programming-for-mac-os-x-for-
dummies-1082466
(Ebook) Cocoa programming for Mac OS X for dummies by Tejkowski, Erick
ISBN 9780470432891, 9780470477908, 9781282031296, 0470432896,
0470477903, 1282031295

https://ebooknice.com/product/cocoa-programming-for-mac-os-x-for-
dummies-12031978

(Ebook) Mac OS X Programming by Dan Sydow ISBN 9780735711686,


0735711682

https://ebooknice.com/product/mac-os-x-programming-983170

(Ebook) MAC OS X UNIX Toolbox: 1000+ Commands for the Mac OS X by


Christopher Negus ISBN 9780470478363, 0470478365

https://ebooknice.com/product/mac-os-x-unix-toolbox-1000-commands-for-
the-mac-os-x-1793620

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason; Viles, James


ISBN 9781459699816, 9781743365571, 9781925268492, 1459699815,
1743365578, 1925268497

https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

(Ebook) iPhone Programming: The Big Nerd Ranch Guide by Joe Conway,
Aaron Hillegass; [Conway, Joe; Hillegass, Aaron] ISBN 9780321706249,
0321706242

https://ebooknice.com/product/iphone-programming-the-big-nerd-ranch-
guide-21964744
Cocoa® Programming for Mac® OS X, Fourth Edition

Aaron Hillegass
Adam Preble

Upper Saddle River, NJ • Boston • Indianapolis • San Francisco


New York • Toronto • Montreal • London • Munich • Paris • Madrid
Capetown • Sydney • Tokyo • Singapore • Mexico City
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear
in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals.

The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no
responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the
information or programs contained herein.

The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions
and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please
contact:

U.S. Corporate and Government Sales


(800) 382-3419
corpsales@pearsontechgroup.com

For sales outside the United States, please contact:

International Sales
international@pearson.com

Visit us on the Web: informit.com/aw

Library of Congress Cataloging-in-Publication Data


Hillegass, Aaron.
Cocoa programming for Mac OS X / Aaron Hillegass, Adam Preble.—4th ed.
p. cm.
Includes index.
ISBN 978-0-321-77408-8 (pbk. : alk. paper)
1. Cocoa (Application development environment) 2. Operating systems
(Computers) 3. Mac OS. 4. Macintosh (Computer)—Programming. I. Preble, Adam. II. Title.

QA76.76.O63H57145 2012
005.26'8—dc23
2011034459

Copyright © 2012 Pearson Education, Inc.

All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the
publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical,
photocopying, recording, or likewise. To obtain permission to use material from this work, please submit a written request to Pearson Education, Inc.,
Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your request to (201) 236-3290.

ISBN-13: 978-0-321-77408-8
ISBN-10: 0-321-77408-6

Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana.
First printing, November 2011
For Aaron’s sons, Walden and Otto

and

For Adam’s daughter, Aimee


Contents

Preface
Acknowledgments

Chapter 1 Cocoa: What Is It?


A Little History
Tools
Language
Objects, Classes, Methods, and Messages
Frameworks
How to Read This Book
Typographical Conventions
Common Mistakes
How to Learn

Chapter 2 Let’s Get Started


In Xcode
Create a New Project
The main Function
In Interface Builder
The Utility Area
The Blank Window
Lay Out the Interface
The Dock
Create a Class
Create an Instance
Make Connections
A Look at Objective-C
Types and Constants in Objective-C
Look at the Header File
Edit the Implementation File
Build and Run
awakeFromNib
Documentation
What Have You Done?
Chronology of an Application

Chapter 3 Objective-C
Creating and Using Instances
Using Existing Classes
Sending Messages to nil
NSObject, NSArray, NSMutableArray, and NSString
“Inherits from” versus “Uses” or “Knows About”
Creating Your Own Classes
Creating the LotteryEntry Class
Changing main.m
Implementing a description Method
Writing Initializers
Initializers with Arguments
The Debugger
What Have You Done?
Meet the Static Analyzer
For the More Curious: How Does Messaging Work?
Challenge

Chapter 4 Memory Management


Living with Manual Reference Counting
Leak-Free Lottery
dealloc
Autoreleasing Objects
The Retain-Count Rules
Accessor Methods
Living with ARC
Strong References
Weak References
ARC Odds and Ends

Chapter 5 Target/Action
Some Commonly Used Subclasses of NSControl
NSButton
NSSlider
NSTextField
Start the SpeakLine Example
Lay Out the XIB File
Making Connections in Interface Builder
Implementing the SpeakLineAppDelegate Class
For the More Curious: Setting the Target Programmatically
Challenge
Debugging Hints

Chapter 6 Helper Objects


Delegates
The NSTableView and Its dataSource
SpeakLineAppDelegate Interface File
Lay Out the User Interface
Make Connections
Edit SpeakLineAppDelegate.m
Common Errors in Implementing a Delegate
Many Objects Have Delegates
For the More Curious: How Delegates Work
Challenge: Make a Delegate
Challenge: Make a Data Source

Chapter 7 Key-Value Coding and Key-Value Observing


Key-Value Coding
Bindings
Key-Value Observing
Making Keys Observable
Properties
Attributes of a Property
For the More Curious: Key Paths
For the More Curious: Key-Value Observing

Chapter 8 NSArrayController
Starting the RaiseMan Application
RMDocument.xib
Key-Value Coding and nil
Add Sorting
For the More Curious: Sorting without NSArrayController
Challenge 1
Challenge 2

Chapter 9 NSUndoManager
NSInvocation
How the NSUndoManager Works
Adding Undo to RaiseMan
Key-Value Coding and To-Many Relationships
Key-Value Observing
Undo for Edits
Begin Editing on Insert
For the More Curious: Windows and the Undo Manager

Chapter 10 Archiving
NSCoder and NSCoding
Encoding
Decoding
The Document Architecture
Info.plist and NSDocumentController
NSDocument
NSWindowController
Saving and NSKeyedArchiver
Loading and NSKeyedUnarchiver
Setting the Extension and Icon for the File Type
For the More Curious: Preventing Infinite Loops
For the More Curious: Creating a Protocol
For the More Curious: Automatic Document Saving
For the More Curious: Document-Based Applications without Undo
Universal Type Identifiers

Chapter 11 Basic Core Data


NSManagedObjectModel
Interface
View-Based Table Views
Connections and Bindings
How Core Data Works
For the More Curious: View-Based versus Cell-Based Table Views
Challenge

Chapter 12 NIB Files and NSWindowController


NSPanel
Adding a Panel to the Application
Setting Up the Menu Item
AppController.m
Preferences.xib
PreferenceController.m
For the More Curious: NSBundle
Challenge

Chapter 13 User Defaults


NSDictionary and NSMutableDictionary
NSDictionary
NSMutableDictionary
NSUserDefaults
Precedence of Types of Defaults
Setting Defaults
The Identifier for the Application
Create Keys for the Names of the Defaults
Register Defaults
Letting the User Edit the Defaults
Using the Defaults
Suppressing the Creation of Untitled Documents
Setting the Background Color on the Table View
For the More Curious: NSUserDefaultsController
For the More Curious: Reading and Writing Defaults from the Command Line
Challenge

Chapter 14 Using Notifications


What Notifications Are and Are Not
What Notifications Are Not
NSNotification
NSNotificationCenter
Posting a Notification
Registering as an Observer
Handling the Notification When It Arrives
The userInfo Dictionary
For the More Curious: Delegates and Notifications
Challenge

Chapter 15 Using Alert Panels


Make the User Confirm the Deletion
Challenge

Chapter 16 Localization
Localizing a NIB File
String Tables
Creating String Tables
Using the String Table
For the More Curious: ibtool
For the More Curious: Explicit Ordering of Tokens in Format Strings

Chapter 17 Custom Views


The View Hierarchy
Get a View to Draw Itself
Create an Instance of a View Subclass
Size Inspector
drawRect
Drawing with NSBezierPath
NSScrollView
Creating Views Programmatically
For the More Curious: Cells
For the More Curious: isFlipped
Challenge

Chapter 18 Images and Mouse Events


NSResponder
NSEvent
Getting Mouse Events
Using NSOpenPanel
Change the XIB File
Edit the Code
Composite an Image onto Your View
The View’s Coordinate System
Autoscrolling
For the More Curious: NSImage
Challenge

Chapter 19 Keyboard Events


NSResponder
NSEvent
Create a New Project with a Custom View
Lay Out the Interface
Make Connections
Write the Code
For the More Curious: Rollovers
The Fuzzy Blue Box

Chapter 20 Drawing Text with Attributes


NSFont
NSAttributedString
Drawing Strings and Attributed Strings
Making Letters Appear
Getting Your View to Generate PDF Data
For the More Curious: NSFontManager
Challenge 1
Challenge 2

Chapter 21 Pasteboards and Nil-Targeted Actions


NSPasteboard
Add Cut, Copy, and Paste to BigLetterView
Nil-Targeted Actions
Looking at the XIB File
For the More Curious: Which Object Sends the Action Message?
For the More Curious: UTIs and the Pasteboard
Custom UTIs
For the More Curious: Lazy Copying
Challenge 1
Challenge 2

Chapter 22 Categories
Add a Method to NSString
For the More Curious: Declaring Private Methods

Chapter 23 Drag-and-Drop
Make BigLetterView a Drag Source
Starting a Drag
After the Drop
Make BigLetterView a Drag Destination
registerForDraggedTypes:
Add Highlighting
Implement the Dragging Destination Methods
Add a Second BigLetterView
For the More Curious: Operation Mask

Chapter 24 NSTimer
Lay Out the Interface
Make Connections
Add Code to TutorController
For the More Curious: NSRunLoop
Challenge

Chapter 25 Sheets
Adding a Sheet
Add Outlets and Actions
Lay Out the Interface
Add Code
For the More Curious: contextInfo
For the More Curious: Modal Windows

Chapter 26 Creating NSFormatters


A Basic Formatter
Create ColorFormatter.h
Edit the XIB File
NSColorList
Searching Strings for Substrings
Implement the Basic Formatter Methods
The Delegate of the NSControl Class
Checking Partial Strings
Formatters That Return Attributed Strings
For the More Curious: NSValueTransformer

Chapter 27 Printing
Dealing with Pagination
For the More Curious: Are you Drawing to the Screen?
Challenge

Chapter 28 Web Services


RanchForecast Project
NSURLConnection
Add XML Parsing to ScheduleFetcher
Lay Out the Interface
Write Controller Code
Opening URLs
Challenge: Add a WebView

Chapter 29 Blocks
Block Syntax
Memory and Objects within Blocks
Availability of Blocks
RanchForecast: Going Asynchronous
Receiving the Asynchronous Response
Challenge: Design a Delegate

Chapter 30 Developing for iOS


Porting RanchForecast to iOS
ScheduleFetcher
RootViewController
Add a Navigation Controller
ScheduleViewController
UITableViewController
Pushing View Controllers
Challenge

Chapter 31 View Swapping


Get Started
Create the ManagedViewController Class
Create ViewControllers and their XIB files
Add View Swapping to MyDocument
Resizing the Window

Chapter 32 Core Data Relationships


Edit the Model
Create Custom NSManagedObject Classes
Employee
Department
Lay Out the Interface
EmployeeView.xib
Events and nextResponder

Chapter 33 Core Animation


Scattered
Implicit Animation and Actions
More on CALayer
Challenge 1
Challenge 2

Chapter 34 Concurrency
Multithreading
A Deep Chasm Opens Before You
Simple Cocoa Background Threads
Improving Scattered: Time Profiling in Instruments
Introducing Instruments
NSOperationQueue
Multithreaded Scattered
Thread Synchronization
For the More Curious: Faster Scattered
Challenge

Chapter 35 Cocoa and OpenGL


A Simple Cocoa/OpenGL Application
Lay Out the Interface
Write Code

Chapter 36 NSTask
ZIPspector
Asynchronous Reads
iPing
Challenge: .tar and .tgz files

Chapter 37 Distributing Your App


Build Configurations
Preprocessor Macros and Using Build Configurations to Change Behavior
Creating a Release Build
Application Sandboxing
Entitlements
Mediated File Access and Powerbox
The Mac App Store

Chapter 38 The End


Index
Preface

If you are developing applications for the Mac, or are hoping to do so, this book is just the resource you need. Does it cover everything you will ever want
to know about programming for the Mac? Of course not. But it does cover probably 80% of what you need to know. You can find the remaining 20%—the
20% that is unique to you—in Apple’s online documentation.
This book, then, acts as a foundation. It covers the Objective-C language and the major design patterns of Cocoa. It will also get you started with the two
most commonly used developer tools: Xcode and Instruments. After reading this book, you will be able to understand and utilize Apple’s online
documentation.
There is a lot of code in this book. Through that code, we will introduce you to the idioms of the Cocoa community. Our hope is that by presenting
exemplary code, we can help you to become more than a Cocoa developer—a stylish Cocoa developer.
This fourth edition includes technologies introduced in Mac OS X 10.6 and 10.7. These include Xcode 4, ARC, blocks, view-based table views, and the
Mac App Store. We have also devoted one chapter to the basics of iOS development.
This book is written for programmers who already know some C programming and something about objects. If you don’t know C or objects, you should
first read Objective-C Programming: The Big Nerd Ranch Guide. You are not expected to have any experience with Mac programming. This hands-on
book assumes that you have access to Mac OS X and the developer tools. Xcode 4.2, Apple’s IDE, is available for free. If you are a member of the paid
Mac or iOS Developer Programs, Xcode can also be downloaded from the Apple Developer Connection Web site (http://developer.apple.com/).
Enrollment in these programs enables you to submit your applications to the Mac and iOS App Stores, respectively.
We have tried to make this book as useful for you as possible, if not indispensable. That said, we’d love to hear from you at
cocoabook@bignerdranch.com if you have any suggestions for improving it.
—Aaron Hillegass and Adam Preble
Acknowledgments

Creating this book required the efforts of many people. We want to thank them for their help. Their contributions have made this a better book than we
could have ever written alone.
Thanks to the students who took the Cocoa programming course at the Big Nerd Ranch. They helped us work the kinks out of the exercises and
explanations that appear here. Their curiosity inspired us to make the book more comprehensive, and their patience made it possible.
Thank you to all the readers of the first three editions, who made such great suggestions on our forums (http://forums.bignerdranch.com/).
Thank you to all the instructors at the Ranch, who made great additions and caught many of our most egregious errors.
A final shout out to the people at Addison-Wesley, who took our manuscript and made it into a book. They put the book on trucks and convinced
bookstores to put it on the shelves. Without their help, it would still be just a stack of paper.
Chapter 1. Cocoa: What Is It?

A Little History

The story of Cocoa starts with a delightful bit of history. Once upon a time, two guys named Steve started a company called Apple Computer in their
garage. The company grew rapidly, so they hired an experienced executive named John Sculley to be its CEO. After a few conflicts, John Sculley moved
Steve Jobs to a position where he had no control over the company at all. Steve Jobs left to form another computer company, called NeXT Computer.
NeXT hired a small team of brilliant engineers. This small team developed a computer, an operating system, a printer, a factory, and a set of development
tools. Each piece was years ahead of competing technologies, and the masses were excited and amazed. Unfortunately, the excited masses did not buy
either the computer or the printer. In 1993, the factory was closed, and NeXT Computer, Inc., became NeXT Software, Inc.
The operating system and the development tools continued to sell under the name NeXTSTEP. While the average computer user had never heard of
NeXTSTEP, it was very popular with several groups: scientists, investment banks, and intelligence agencies. These were people who developed new
applications every week, and they found that NeXTSTEP enabled them to implement their ideas faster than any other technology.
What was this operating system? NeXT decided to use Unix as the core of NeXTSTEP. It relied on the source code for BSD Unix from the University of
California at Berkeley. Why Unix? Unix crashed much less frequently than Microsoft Windows or Mac OS and came with powerful, reliable networking
capabilities.
Apple has made the source code to the Unix part of Mac OS X available under the name Darwin. A community of developers continues to work to
improve Darwin. You can learn more about Darwin at www.macosforge.org.
NeXT then wrote a window server for the operating system. A window server takes events from the user and forwards them to the applications. The
application then sends drawing commands back to the window server to update what the user sees. One of the nifty things about the NeXT window server
is that the drawing code that goes to the window server is the same drawing code that would be sent to the printer. Thus, a programmer has to write the
drawing code only once, and it can then be used for display on the screen or printing. In the NeXTSTEP days, programmers were writing code that
generated PostScript. With Mac OS X, programmers are writing code that uses the Core Graphics framework (also known as Quartz). Quartz can
composite those graphics onto the screen, send them to the printer, or generate PDF data. The Portable Document Format is an open standard for
vector graphics created by the Adobe Corporation.
If you have used Unix machines before, you are probably familiar with the X window server. The window server for Mac OS X is completely different but
fulfills the same function as the X window server: It gets events from the user, forwards them to the applications, and puts data from the applications onto
the screen.
NeXTSTEP came with a set of libraries and tools to enable programmers to deal with the window manager in an elegant manner. The libraries were
called frameworks. In 1993, the frameworks and tools were revised and renamed OpenStep, which was itself later renamed Cocoa.
As shown in Figure 1.1, the window server and your application are Unix processes. Cocoa enables your application to receive events from the window
server and draw to the screen.

Figure 1.1. Where Is Cocoa?

Programming with the frameworks is done in a language called Objective-C. Like C++, Objective-C is a C programming language extension that made it
object-oriented. Unlike C++, Objective-C is weakly typed and extremely powerful. With power comes responsibility: Objective-C also allows programmers
to make ridiculous errors. Objective-C is a very simple addition to C, and you will find it very easy to learn.
Programmers loved OpenStep. It enabled them to experiment more easily with new ideas. In fact, Tim Berners-Lee developed the first Web browser and
the first Web server on NeXTSTEP. Securities analysts could code and test new financial models much more quickly. Colleges could develop the
applications that made their research possible. We don’t know what the intelligence community was using it for, but they bought thousands of copies of
OpenStep. Because the OpenStep development tools were so useful, they were ported to Solaris and Windows NT, and the NeXTSTEP operating
system was ported to most of the popular CPUs of the day: Intel, Motorola, Hewlett-Packard’s PA-RISC, and SPARC. (Oddly enough, OpenStep didn’t
run on a Mac until the first version of Mac OS X Server, known as Rhapsody, shipped in 1999.)
For many years, Apple Computer had been working to develop an operating system with many of the features of NeXTSTEP. This effort was known as
Copland. Project Copland gradually spun out of control, and Apple finally decided to pull the plug and buy the next version of Mac OS from another
company. After surveying the existing operating systems, Apple selected NeXTSTEP. Because NeXT was small, Apple simply bought the whole
company in December 1996.
NeXTSTEP became Mac OS X. It is Unix underneath, and you can get all the standard Unix programs (such as the Apache Web server) on Mac OS X. It
is extremely stable and the user interface is spectacular.
In 2008, the iOS SDK, as it would eventually be called, was announced. Apple’s incredibly successful App Store has brought an audience of millions to
iOS developers, many of whom are also Cocoa developers on the Mac. Cocoa Touch is built on top of the very same foundations as Cocoa, and indeed
many of the classes are identical. More important, the principles and design patterns are essentially unchanged. In 2010, just ahead of Mac OS X Lion,
Apple introduced the Mac App Store, bringing the same ease of distribution to Mac developers.
You, the developer, are going to love Mac OS X because Cocoa will enable you to write full-featured applications in a radically more efficient and elegant
manner.

Tools

You will love Cocoa but perhaps not immediately. First, you will learn the basics. Let’s start with the tools that you will use.
All the tools for Cocoa development come as part of the Mac OS X Developer Tools, and you get them for free with Mac OS X. Although the Developer
Tools will add about a dozen handy applications to your system, you will use one application primarily: Xcode. Behind the scenes, either the LLVM (Low
Level Virtual Machine) or the GNU C compiler (gcc) will be used to compile your code, and the GNU debugger (gdb) or the LLDB (Low Level Debugger)
will help you find your errors.
Xcode tracks all the resources that will go into an application: code, images, sounds, and so on. You will edit your code in Xcode, and Xcode can compile
and launch your application. Xcode can also be used to invoke and control the debugger. We strongly recommend using Xcode 4.2 or greater when trying
the exercises in this book. While many of the concepts covered can be applied in the Xcode 3 and even earlier, the style of memory management used
(ARC) requires the Xcode 4.2 compiler.
Inside Xcode, you will use the Interface Builder editor as a GUI builder. It edits XIB files, allowing you to lay out windows and add widgets to those
windows. It is, however, much more. Interface Builder allows the developer to create objects and edit their attributes. Most of those objects are UI
elements such as buttons and text fields, but some will be instances of classes that you create.
You will also use Instruments to profile your application’s CPU, memory, and filesystem usage. Instruments can also be used to debug memory-
management issues. Instruments is built on top of dtrace, which makes it possible to create new instruments.

Language

This book uses Objective-C for all the examples. Objective-C is a simple and elegant extension to C, and mastering it will take about two hours if you
already know C and an object-oriented language such as Java or C++.
It is possible to develop Cocoa applications in Ruby or Python. This book will not cover that technique, but there is plenty of information on the Web. To
understand that information, you will still need a working knowledge Objective-C.
With Mac OS 10.5, Objective-C underwent a major revision. All the code in this book is Objective-C 2.0, and almost all of the code in this book uses ARC
for memory management. We will discuss memory management in further detail in Chapter 4.
The Objective-C code will be compiled by the LLVM compiler. The compiler allows you to freely mix C, C++, and Objective-C code in a single file.
The debugger, gdb or lldb, will be used to set breakpoints and browse variables at runtime. Objective-C gives you a lot of freedom to do dumb things; you
will be glad to have a decent debugger.

Objects, Classes, Methods, and Messages

All Cocoa programming is done using object-oriented concepts. This section very briefly reviews terms used in object-oriented programming. If you have
not done any object-oriented programming before, we recommend that you read The Objective-C Language. The PDF file for the book is on the Apple
Web site, The URL is http://developer.apple.com/library/mac/documentaion/Cocoa/Conceptual/ObjectiveC/ObjC.pdf.
What is an object? An object is like a C struct: It takes up memory and has variables inside it. The variables in an object are called instance variables. So
when dealing with objects, the first questions we typically ask are: How do you allocate space for one? What instance variables does the object have?
How do you destroy the object when you are done with it?
Some of the instance variables of an object will be pointers to other objects. These pointers enable one object to “know about” another.
Classes are structures that can create objects. Classes specify the variables that the object has and are responsible for allocating memory for the object.
We say that the object is an instance of the class that created it (Figure 1.2).

Figure 1.2. Classes Create Instances

An object is better than a struct because an object can have functions associated with it. We call the functions methods. To call a method, you send the
object a message (Figure 1.3).
Figure 1.3. Messages Trigger Methods

Frameworks

A framework is a collection of classes that are intended to be used together. That is, the classes are compiled together into a reusable library of code.
Any related resources are put into a directory with the library. The directory is renamed with the extension .framework. You can find the built-in
frameworks for your machine in /System/Library/Frameworks. Cocoa is made up of three frameworks:
1. Foundation: Every object-oriented programming language needs the standard value, collection, and utility classes. Strings, dates, lists, threads,
and timers are in the Foundation framework.
2. AppKit: All things related to the user interface are in the AppKit framework. These include windows, buttons, text fields, events, and drawing
classes. You will also see this framework called the ApplicationKit.
3. Core Data: Core Data makes it easy to save your objects to a file and then reload them into memory. We say that it is a persistence framework.
We will focus on these three frameworks because they are the most commonly used. Once you have mastered these, the other frameworks will be easier
to understand. Numerous other frameworks handle such duties as encryption, QuickTime, and CD burning.
You can also create your own frameworks from the classes that you create. Typically, if a set of classes is used in several applications, you will want to
turn them into a framework.

How to Read This Book

This book acts as the guide through activities to help you understand Cocoa programming. Often, we will ask you to do something and explain the details
or theory afterward. If you are confused, read a little more. Usually, the help you seek will be only a paragraph or two away.
If you are still stumped, you can get help on the Web site for this book: www.bignerdranch.com/books. Errata, hints, and examples are listed there as well.
Also, all the solutions for the exercises can be downloaded from there. You can also post questions about the book and concepts discussed in the book
on the Big Nerd Ranch forums (http://forums.bignerdranch.com/).
Each chapter will guide you through the process of adding features to an application. This is not, however, a cookbook. This book teaches ideas, and the
exercises show these ideas in action. Don’t be afraid to experiment.
There are about 300 classes in the Cocoa frameworks. All are documented in the online reference (accessed through Xcode’s Help menu). Cocoa
programmers spend a lot of time browsing through these pages. But until you understand a lot about Cocoa, it is hard to find the right starting place in
your search for answers. As this book introduces you to a new class, look it up in the reference. You may not understand everything you find there, but
browsing through the reference will give you some appreciation for the richness of the frameworks. When you reach the end of this book, the reference will
become your guide.
Most of the time, Cocoa fulfills the following promise: Common things are easy, and uncommon things are possible. If you find yourself writing many lines
of code to do something rather ordinary, you are probably on the wrong track.

Typographical Conventions

To make the book easier to comprehend, we’ve used several typographical conventions.
In Objective-C, class names are always capitalized. In this book, we’ve also made them appear in a monospaced bold font. In Objective-C, method
names start with a lowercase letter. Method names will also appear in a monospaced bold font. For example, you might see “The class NSObject has the
method dealloc.”
Other literals, including instance variable names that you would see in code, will appear in a regular monospaced font. Also, filenames will appear in this
same font. Thus, you might see “In MyClass.m, set the variable favoriteColor to nil.”
Code samples in this book appear in the regular monospaced font. New portions, which you will need to type yourself, will appear in bold.

Common Mistakes

Having watched many, many people work through this material, we’ve seen the same mistakes made hundreds of times. Two mistakes are particularly
common: capitalization mistakes and forgotten connections.
Capitalization mistakes happen because C and Objective-C are case-sensitive languages—the compiler does not consider Foo and foo to be the same
thing. If you are having trouble making something compile, check to make sure that you have typed all the letters in the correct case.
When creating an application, you will use the Interface Builder editor to connect objects together. Forgotten connections usually allow your application to
build and run but result in aberrant behavior. If your application is misbehaving, go back to Interface Builder and check your connections.
It is easy to miss some warnings the first time a file is compiled. Because Xcode does incremental compiles, you may not see those warnings again
unless you clean and rebuild the project. If you are stuck, cleaning and rebuilding is certainly worth a try.

How to Learn

All sorts of people come to our class: the bright and the not so bright, the motivated and the lazy, the experienced and the novice. Inevitably, the people
who get the most from the class share one characteristic: They remain focused on the topic at hand.
The first trick to maintaining focus is to get enough sleep: ten hours of sleep each night while you are studying new ideas. Before dismissing this idea, try
it. You will wake up refreshed and ready to learn. Caffeine is not a substitute for sleep.
The second trick is to stop thinking about yourself. While learning something new, many students will think, “Damn, this is hard for me. I wonder if I am
stupid.” Because stupidity is such an unthinkably terrible thing in our culture, the students will then spend hours constructing arguments that explain why
they are intelligent yet are having difficulties. The moment you start down this path, you have lost your focus.
Aaron used to have a boss named Rock. Rock had earned a degree in astrophysics from Cal Tech and had never had a job that used his knowledge of
the heavens. He was once asked if he regretted getting the degree. “Actually, my degree in astrophysics has proved to be very valuable,” he said. “Some
things in this world are just hard. When I am struggling with something, I sometimes think ‘Damn, this is hard for me. I wonder if I am stupid,’ and then I
remember that I have a degree in astrophysics from Cal Tech; I must not be stupid.”
Before going any further, assure yourself that you are not stupid and that some things are just hard. Armed with this silly affirmation and a well-rested
mind, you are ready to conquer Cocoa.
Exploring the Variety of Random
Documents with Different Content
Begum Kothee. He had with him the 93d Highlanders, the 4th
Punjaub Rifles, and 1000 Goorkhas, and was aided in the assault by
Adrian Hope. His troops speedily secured the whole block of
buildings, and inflicted a very heavy loss on the enemy. The attack
was one of a desperate character, and was characterised by Sir Colin
as ‘the sternest struggle which occurred during the siege.’ From that
point Napier pushed his engineering approaches with great
judgment through the enclosures, by the aid of the sappers and the
heavy guns; the troops immediately occupying the ground as he
advanced, and the mortars being moved from one position to
another as the ground was won on which they could be placed.
Outram was not idle during these operations. He obtained
possession of the iron bridge, leading over the river from the
cantonment to the city, and swept away the enemy from every part
of the left bank of the river between that bridge and the Padishah
Bagh; thus leaving him in a position to enfilade the central and inner
lines of defence established by the enemy among the palaces.
It was while these serious and important operations were in
progress, on the 11th of March, that the commander-in-chief was
called upon to attend to a ceremonial affair, from which he would
doubtless have willingly been spared. The preceding chapters have
shewn how Jung Bahadoor, descending from the Nepaulese
mountains with an army of 9000 Goorkhas, rendered a little service
in the Goruckpore and Jounpoor districts, and then advanced into
Oude to assist in the operations against Lucknow. His movements
had been dilatory; and Sir Colin was forced to arrange all the details
of the siege as if no reliance could be placed in this ally. At length,
however, on the afternoon of the 11th, Jung Bahadoor appeared at
the Dil Koosha; he and Sir Colin met for the first time. The meeting
was a curious one. The Nepaul chieftain, thoroughly Asiatic in
everything, prepared for the interview as one on which he might
lavish all his splendour of gold, satin, pearls, and diamonds; the old
Highland officer, on the other hand, plain beyond the usual plainness
of a soldier in all that concerned personal indulgences,[145] was
somewhat tried even by the necessity for his full regimentals and
decorative appendages. A continuous battle was going on, in which
he thought of his soldiers’ lives, and of the tactics necessary to
insure a victory; at such a time, and in such a climate, he would
gladly have dispensed with the scarlet and the feathers of his rank,
and of the oriental compliments in which truth takes little part. A
tasteful canopy was prepared in front of Sir Colin’s mess-tent; and
here were assembled the commander-in-chief, Archdale Wilson,
Hope Grant, a glittering group of staff-officers and aids-de-camp, a
Highland guard of honour, an escort of Lancers, bands, pipers,
drums, flags, and all the paraphernalia for a military show. Sir Colin
was punctual; Jung Bahadoor was not. Sir Colin, his thoughts all the
while directed towards Lugard’s operations at the Begum Kothee, felt
the approaching ceremony, and the delay in beginning it, as a sore
interruption. At length the Nepaulese chieftain appeared. Jung
Bahadoor had, as Nepaulese ambassador, made himself famous in
London a few years before, by his gorgeous dress and lavish
expenditure; and he now appeared in fully as great splendour. The
presentations, the greetings, the compliments, the speeches, were
all of the wonted kind; but when Captain Hope Johnstone, as one of
the officers of the chief of the staff, entered to announce that ‘the
Begum Kothee is taken,’ Sir Colin broke through all ceremony,
expressed a soldier’s pleasure at the news, and brought the
interview to a termination. Jung Bahadoor returned to his own
camp; and the commander-in-chief instantly resumed his ordinary
military duties. Sir Colin was evidently somewhat puzzled to know
how best to employ his gorgeous colleague; although his courtesy
would not allow him to shew it. The Goorkhas moved close to the
canal on the 13th; and on the following day Sir Colin requested Jung
Bahadoor to cross the canal, and attack the suburbs to the left of
Banks’s house. As he was obliged, just at that critical time, to mass
all the available strength of his British troops in the double attack
along the banks of the Goomtee, the commander-in-chief had few to
spare for his left wing; and he speaks of the troops of the Nepaulese
leader as being ‘most advantageously employed for several days,’ in
thus covering his left.
We return to the siege operations. So great had been the progress
made on the 11th, that the development of the commander-in-
chief’s strategy became every hour more and more clear. Outram’s
heavy fire with guns and mortars produced great effect on the Kaiser
Bagh; while the Begum Kothee became a post from which an attack
could be made on the Emanbarra, a large building situated between
the Begum Kothee and the Kaiser Bagh.[146] The Begum Kothee
palace, when visited by the officers of the staff on the morning of
the 12th, astonished them by the strength which the enemy had
given to it. The walls were so loopholed for musketry, the bastions
and cannon were so numerous, the ditch around it was so deep, and
the earthen rampart so high, that all marvelled how it came to be so
easily captured on the preceding day. The enemy might have held it
against double of Lugard’s force, had they not been paralysed by the
bayonet. It was a strange sight, on the following morning, to see
Highlanders and Punjaubees roaming about gorgeous saloons and
zenanas, still containing many articles of dress and personal
ornaments which the ladies of the palace had not had time to carry
away with them. Whither the inmates had fled, the conquerors at
that time did not know, and in all probability did not care. It was a
strange and unnatural sight; splendour and blood appeared to have
struggled for mastery in the various courts and rooms of the palace,
many contests having taken place with small numbers of the enemy.
[147]
From this building, we have said, Sir Colin determined that
progress should be made towards the Emanbarra, not by open
assault, but by sapping through a mass of intermediate buildings.
Gateway of the Emanbarra at Lucknow.

The 12th was the day when the sapping commenced; but so many
and so intricate were the buildings, that three days were occupied in
this series of operations; seeing that it was necessary to destroy or
at least to render innoxious such houses as might have concealed
large bodies of the enemy. Lugard’s troops having been hotly
engaged on the 11th, they were now relieved by others under
Franks. The work was of formidable character; for the flat roofs of
many of the houses were covered with two or three feet of earth,
baked in the sun, and loopholed for musketry. Every such house had
to be well scrutinised, before a further advance was made. The
sappers made passages, either actually underground, or through the
lower portions of the walls and enclosures surrounding the buildings.
On the 13th these approaches were so far completed that a large
number of guns and mortars could be brought forward, and placed
in position for bombarding the Emanbarra. On this day, too, Jung
Bahadoor’s troops took possession of a mass of suburban houses
southward of the city, between Sir Colin’s camp and the Alum Bagh;
after which the commander-in-chief paid a return visit to the
Nepaulese chieftain, who strove to display still more magnificence
than at the former interview.
The 14th of March was one of the busy days of the siege. The sap
was carried on so successfully that the Emanbarra could be
bombarded by heavy guns and mortars, and then taken. Directly this
was done, Brasyer’s Sikhs, pressing forward in pursuit of the fleeing
enemy, entered the Kaiser Bagh—the third or inner line of defence
having been turned without a single gun being fired from it.
Supports were quickly thrown in, and the British troops found
themselves speedily in a part of the city already well known to
Campbell and Outram during their operations of November—
surrounded by the Mess-house, the Taree Kothee, the Motee Mehal,
and the Chuttur Munzil. All these buildings were near them, and all
were occupied by them before night closed in. As fast as the infantry
seized these several positions, so did the engineers proceed to
secure the outposts towards the south and west. As in many other
cases when it was the lot of the English in India to fight their
greatest battles, or bear their greatest sufferings, on Sundays; so
was it on a Sunday that these busy operations of the 14th took
place. The front walls of the Kaiser Bagh and the Motee Mehal were
extensively mined; insomuch that when the artillery had effected its
dread work, the infantry could approach much more safely than if
exposed to the sight of sharpshooters and matchlockmen. It is true
that neither English nor Highlanders, neither Sikhs nor Goorkhas,
would have hesitated to rush forward and storm these buildings
without a sap; but as Sir Colin was well supplied with heavy guns, he
acted steadily on the plan of employing them as much as possible
before sending on his men—feeling that the loss of men would be
more difficult to replace than that of guns and missiles, at such a
time and in such a country. In his dispatch relating to the operations
of the 14th of March, he said: ‘The day was one of continued
exertion; and every one felt that, although much remained to be
done before the final expulsion of the rebels, the most difficult part
of the undertaking had been overcome. This is not the place for a
description of the various buildings sapped into or stormed. Suffice it
to say that they formed a range of massive palaces and walled
courts of vast extent, equalled perhaps, but not surpassed, in any
capital of Europe. Every outlet had been covered by a work, and on
every side were prepared barricades and loopholed parapets. The
extraordinary industry evinced by the enemy in this respect has been
really unexampled. Hence the absolute necessity for holding the
troops in hand, till at each successive move forward the engineers
reported to me that all which could be effected by artillery and the
sappers had been done, before the troops were led to the assault.’
A little must here be said concerning the share which Sir James
Outram had in the operations of the 12th and two following days. All
his tactics, on the left bank of the river, were especially intended to
support those of the commander-in-chief on the right bank. On the
12th his heavy guns, at and near the Padishah Bagh, poured forth a
torrent of shot, to dislodge the enemy from certain positions near
the city. His head-quarters were established under a small tope of
trees near a ruined mosque; and he, as well as Lugard and Walpole,
lived as simply as possible under tents. The Padishah Bagh itself—a
suburban palace with beautiful saloons, halls, terraces, orange-
groves and fountains—was held by H.M. 23d. The left bank of the
river being occupied as far up as the iron suspension bridge, Outram
planted two or three guns to guard that position from any hostile
attack from the north; while two or three regiments of his own
infantry, in convenient spots near the bridge, kept up a musketry-fire
against such of the enemy as were visible and within reach on the
opposite or city side of the river. This musketry-fire was continued all
day on the 13th, while the batteries of heavy guns were being
brought further and further into position. On the 14th, the same
operations were continued; but the conquest of the Kaiser Bagh was
so sudden and unexpected on this day, that the proceedings on the
left bank of the river were relatively unimportant.
When the morning of the 15th arrived, Sir Colin Campbell felt that
he might call Lucknow his own; for although much remained to be
done, the conquests achieved were vast and important. The
Mahomed Bagh, the Dil Koosha, the Martinière, the Secunder Bagh,
the Emanbarra, the Mess-house, the Shah Munzil, the Motee Mehal,
the Begum Kothee, and the Kaiser Bagh, were all in his hands—
constituting by far the strongest and most important of the palatial
buildings along the banks of the river. Moreover, the natives were
evidently dismayed; vast numbers were leaving the city on the
Rohilcund side; and spies brought information that the rebel leaders
encountered much difficulty in keeping the sepoys steadily at the
defence-works. The progress made by the British had surprised and
alarmed the insurgents, and tended to paralyse their exertions.
Some of the British officers had entertained a belief that the Kaiser
Bagh was the key to the enemy’s position, whereas others had
looked rather to the Begum Kothee. The latter proved to be right.
The enemy had greatly relied on the last-named building; insomuch
that, when it was captured, they rushed in wild confusion to the
Kaiser Bagh, intent rather upon flight than upon a stubborn
resistance. The garrison of the Kaiser Bagh, disconcerted by this
irruption of their brother insurgents, were rendered almost unable,
even if willing, to make a manful resistance. The British were almost
as much surprised by the speedy capture of the Kaiser Bagh, as the
enemy were by the loss of the Begum Kothee. When the great
palace changed hands, the smoke and blood and cries of war were
strangely mingled with the magnificence of kiosks, mosques,
corridors, courts, gardens, terraces, saloons, mirrors, gilding,
chandeliers, tapestry, statues, pictures, and costly furniture, in this
strange jumble of oriental and European splendour.
A soldier loses all his heroism when the hour for prize and plunder
arrives. Those, whether officers or spectators, who have described
the scene which was presented when these Lucknow palaces were
conquered, tell plainly of a period of wild licence and absorbing
greed. On the one hand there were palaces containing vast stores of
oriental and European luxuries; on the other, there were bands of
armed men, brave and faithful, but at the same time poor and
unlettered, who suddenly found themselves masters of all these
splendours, with very little check or supervision on the part of their
officers. At first, in a spirit of triumphant revenge, costly articles
were broken which were too large to be carried away; glass
chandeliers were hurled to the ground, mirrors shattered into
countless fragments, statues mutilated and overturned, pictures
stabbed and torn, doors of costly wood torn from their hinges. But
when this destruction had been wreaked, and when the troops had
forced their way through courts and corridors strewn with sepoys’
brass lotas or drinking-vessels, charpoys, clothing, belts,
ammunition, muskets, matchlocks, swords, pistols, chupatties, and
other evidences of precipitate flight—when this had all occurred,
then did the love of plunder seize hold of the men. The Kaiser Bagh
had been so quickly conquered, that the subaltern officers had not
yet received instructions how to control the movements of the troops
in this matter. Sikhs, Highlanders, English, were soon busily
engaged. In one splendid saloon might be seen a party of Sikhs
melting down gold and silver lace for the sake of the precious
metals; in another, a quantity of shawls, lace, pearls, and
embroidery of gold and silver, was being divided equally among a
group of soldiers. In a sort of treasure-room, apparently belonging
to some high personage, a few men of two British regiments found
caskets and boxes containing diamonds, emeralds, rubies, pearls,
opals, and other gems, made into necklaces, bracelets, earrings,
girdles, &c.; together with gold-mounted pistols, jewel-hilted swords,
saddle-cloths covered with gold and pearls, gold-handled riding-
canes, jewelled cups of agate and jade, japanned boxes filled with
crystal and jade vessels. And, as it appeared that every one felt
himself permitted or at least enabled to retain whatever he could
capture, the camp-followers rushed in and seized all that the soldiers
had left. Coolies, syces, khitmutgars, dooly-bearers, and grass-
cutters, were seen running hither and thither, laden with costly
clothing, swords, firelocks, brass pots, and other articles larger in
bulk than the actual soldiers could readily have disposed of. It was a
saturnalia, during which it is believed that some of the troops
appropriated enough treasure, if converted into its value in money,
to render them independent of labour for the rest of their lives. But
each man kept, in whole or in part, his own secret.
Let us on from this extraordinary scene. The 15th was chiefly
employed in securing what had been captured, removing powder,
destroying mines, and fixing mortars for the further bombardment of
the positions still held by the enemy, on the right bank of the
Goomtee, and in the heart of the city. As the infantry and artillery
could fulfil this duty, without the aid of horse, two bodies of cavalry,
under Walpole and Hope Grant, were sent out to prevent, if possible,
the escape of the enemy on the sides of the city not subject to
immediate attack. One of these generals proceeded towards the
Sundeela road, and the other to that leading to Seetapoor. Whether
this flight of the enemy disappointed or not the expectations of the
commander-in-chief, was a question which he kept to himself. The
city, for all practical military purposes, was twenty miles in
circumference; and he could not have guarded all the outlets without
a very much larger army than that which was at his disposal. Like as
at Sebastopol, the siege was not aided by a complete investiture of
the place besieged. It is possible that the capture of the Kaiser Bagh,
and the consequent flight of the enemy, occurred too early for Sir
Colin to be enabled to put in operation certain manœuvres on the
other side of the city. Be this as it may, large numbers of rebel
sepoys, and a still larger of the regular inhabitants of the city
escaped during the 14th and 15th, mostly over the stone bridge—as
if hopeful of safety in Rohilcund and Upper Oude.
On the 16th Sir James Outram, after ten days of active operation on
the left bank of the Goomtee, crossed over by a bridge of casks
opposite the Secunder Bagh; and he then advanced through the
Chuttur Munzil towards the Residency. To lessen the chance of the
enemy’s retreat as much as possible, he marched right through the
city, not only to the iron bridge near the Residency, but to the stone
bridge near the Muchee Bhowan. All this was an enterprise of
remarkable boldness, for the buildings to be successively conquered
and entered were very numerous. Outram shifted his own head-
quarters to Banks’s house, on the city side of the river; and it was
here that he received a letter from the Begum, or mother of the
young boy-king, containing some sort of proposition for compromise
or cessation of hostilities. Whatever it may have been, no successful
result attended this missive: the progress and conquest went on as
before. His troops, as they advanced to the Chuttur Munzil, the Pyne
Bagh, the Fureed Buksh, and the Taree Kothee, found all these
buildings abandoned by the enemy—who had been too much
dismayed by the operations of the 16th to make a bold stand. At
length he approached the Residency, the enclosed spot whose name
will ever be imperishably associated with Inglis’s defence of the
British garrison, and in which Outram himself had passed many
anxious weeks between September and November. Hardly a building
remained standing within the enclosure; all had been riddled and
shattered during the long period from July to November, and most of
them subsequently destroyed by the enemy. Up to this time
Outram’s march of the 16th through the city had been almost
unopposed; but he now ascertained that the houses and palaces
between the iron and stone bridges were occupied by the enemy in
considerable force. Hard fighting at once commenced here, in which
the 20th, 23d, and 79th regiments were actively engaged. They
advanced at a rapid pace from the Residency towards the iron
bridge. A 9-pounder, planted to command a road by the way, fired
grape into them; but it was speedily captured. By that time the large
guns were brought into position, to play upon the stone bridge, the
Emanbarra of Azof-u-Dowlah, and other structures northwest of the
iron bridge. At that time Grant and his troopers were near the stone
bridge on the left side of the river, while Outram’s guns were firing
on it from the right bank; as a consequence, no more escape was
permitted by that channel; and the fugitives therefore ran along the
right bank of the river, to a part of the open country northwest of
Lucknow, not yet controlled by the English. Many of the rebel sepoys
resolved to make a stand at the Moosa Bagh, a building at the
extreme limits of the city in this direction; but the day was too far
advanced to attack them at that spot; and the troops were glad to
rest for the night in the splendid saloons and courts of the
Emanbarra—one of the grandest among the many grand structures
in Lucknow.
While Outram was engaged in these operations on the 16th,
obtaining a mastery along almost the whole right bank of the river,
the enemy very unexpectedly made an attack on the Alum Bagh,
which was only held by a small English force under Brigadier
Franklyn. Sir Colin Campbell immediately requested Jung Bahadoor
to advance to his left up the canal, and take in reverse the post from
which the enemy was making the attack. The Nepaulese chieftain
performed this service successfully, capturing the post and the guns,
and expelling the enemy.
When the morning of the 17th arrived, the commander-in-chief
found himself so undoubtedly the master of Lucknow, that he was
enabled to dispense with the services of some of his gallant artillery
officers, whose aid was much wanted at Futteghur and elsewhere.
Still, though the great conquest was mainly effected, the minor
details had yet to be filled up. There were isolated buildings in which
small knots of the enemy had fortified themselves; these it would be
necessary to capture. It was also very desirable to check the camp-
followers in their manifest tendency for plundering the shops and
private houses of the city. Sir Colin did not wish the townsmen to
regard him as an enemy; he encouraged them, so far as they had
not been in complicity with the rebels, to return to their homes and
occupations; and it was very essential that those homes should, in
the meantime, be spared from reckless looting. In some of the
streets, pickets of soldiers were placed, to compel the camp-
followers to disgorge the plunder which they had appropriated; and
thus was collected a strange medley of trinkets and utensils, which
the temporary holders gave up with sore unwillingness. Here and
there, where a soldier had a little leisure and opportunity, he would
hold a kind of mock-auction, at which not only camp-followers but
officers would buy treasures for a mere trifle; but these instances
were few, for there was not much ready cash among the
conquerors. Sir Colin found it necessary to issue an order concerning
the plundering system.[148] Outram and Jung Bahadoor took part in a
series of operations, on the 17th, intended to obtain control over the
northwest section of the city. The one set forth from the river, the
other from the vicinity of the Alum Bagh; and during the day they
cleared out many nests of rebels. There was also an action on the
margin of the city, in which the enemy managed to bring together a
considerable force of horse, foot, and artillery; their guns were
captured, however, and themselves put to flight.
Sir Colin, responsible for many places besides Lucknow, and for
many troops besides those under his immediate command, now
made daily changes in the duties of his officers. Major (now
Lieutenant-colonel) Vincent Eyre and Major (now also Lieutenant-
colonel) Turner, two of the most distinguished artillery officers,
departed for Futteghur and Idrapore; and Franklyn went to
Cawnpore. Inglis succeeded Franklyn at the Alum Bagh. Sir Archdale
Wilson and Brigadier Russell took their departure on sick-leave.
A considerable force of the enemy still lingered around the Alum
Bagh, irresolute as to any actual attacks, but loath to quit the
neighbourhood until the last ray of hope was extinguished. With
these rebels Jung Bahadoor had many smart contests. He had been
instructed by Sir Colin to obtain secure possession of the suburbs of
the city near the Char Bagh—the bridge that carried the Cawnpore
road over the canal.
It was on this day, the 17th, and partly in consequence of the
success attending the operations of the Goorkhas, that two English
ladies, Mrs Orr and Miss Jackson, were delivered from the hands of
enemies who had long held them in bondage. It will be remembered
that on the night of the 22d of November,[149] the insurgents in
Lucknow, enraged at the safe evacuation of the Residency by the
British, put to death certain English prisoners who had long been in
confinement in the Kaiser Bagh. Among them were Mr Orr and Sir
Mountstuart Jackson. So far as any authentic news could be
obtained, it appeared that Mrs Orr and Miss Jackson had been
spared; partly, as some said, through the intervention of the Begum.
During the subsequent period of nearly four months, the fate of
those unhappy ladies remained unknown to their English friends. On
the day in question, however (the 17th of March), Captain M’Neil
and Lieutenant Bogle, both attached to the Goorkha force, while
exploring some of the deserted streets in the suburb, were accosted
by a native who asked their protection for his house and property.
The man sought to purchase this protection by a revelation
concerning certain English ladies, who, he declared, were in
confinement in a place known to him. Almost immediately another
native brought a note from Mrs Orr and Miss Jackson, begging
earnestly for succour. M’Neil and Bogle instantly obtained a guard of
fifty Goorkhas, and, guided by the natives, went on their errand of
mercy. After walking through half a mile of narrow streets, doubtful
of an ambush at every turning, they came to a house occupied by
one Meer Wajeed Ali, who held, or had held, some office under the
court. After a little parleying, M’Neil and Bogle were led to an
obscure apartment, where were seated two ladies in oriental
costume. These were the prisoners, who had so long been excluded
from every one of their own country, and who were overwhelmed
with tearful joy at this happy deliverance. It was not clearly known
whether this Meer Wajeed Ali was endeavouring to buy off safety for
himself by betraying a trust imposed in him; but the two English
officers deemed it best to lose no time in securing their
countrywomen’s safety, whether he were a double-dealer or not;
they procured a palanquin, put the ladies into it, and marched off
with their living treasure—proud enough with their afternoon’s work.
When these poor ladies came to tell their sad tale of woe, with
countenances on which marks of deep suffering were expressed, it
became known that, though not exposed to any actual barbarities or
atrocities, like so many of their countrywomen in other parts of
India, their lives had been made very miserable by the unfeeling
conduct of their jailers, who were permitted to use gross and
insulting language in their presence, and to harrow them with
recitals of what Europeans were and had been suffering. They had
had food in moderate sufficiency, but of other sources of solace they
were almost wholly bereft. It was fully believed that they would not
have been restored alive, had the jailer obeyed the orders issued to
him by the Moulvie.
After a day of comparative repose on the 18th, a combined
movement against the Moosa Bagh was organised on the 19th. This
was the last position held by the enemy on the line of the Goomtee,
somewhat beyond the extreme northwest limit of the city. Outram
moved forward directly against the place; Hope Grant cannonaded it
from the left bank; while William Campbell, approaching on the
remote side from the Alum Bagh, prevented retreat in that direction.
Some said the Begum was there, some the Moulvie or fanatic
chieftain; but on this point nothing was known. All that was certain
was that several thousand insurgents, driven from other places, had
congregated within the buildings and courts of the Moosa Bagh.
Outram’s troops started from the Emanbarra on this expedition early
in the morning; he himself joined them from Banks’s house, while Sir
Colin rode over to see in person how the work was effected.
Opposite the Moosa Bagh, which was a large structure surrounded
by an enclosed court, was the residence of Ali Nuckee Khan, vizier or
prime-minister to the deposed King of Oude; and in other parts of
the vicinity were numerous mansions and mosques. If the rebels had
held well together, they might have made a stout resistance here, for
the buildings contained many elements of strength; but discord
reigned; the Begum reproached the thalookdars, the thalookdars the
sepoys; while the Moulvie was suspected of an intention to set up as
King of Oude on his own account. Outram’s column was to make the
direct attack; Hope Grant’s cavalry and horse-artillery were to
command certain roads of approach and exit on the river-side; while
William Campbell’s cavalry, aided by two or three infantry regiments,
were to command the opposite side. The contest can hardly be
called a battle or a siege; for as soon as the rebels clearly
ascertained that the British were approaching, they abandoned court
after court, house after house, and escaped towards the northwest,
by the only avenue available. Although they did not fight, they
escaped more successfully than Sir Colin had wished or intended.
Whether the three movements were not timed in unison, or whether
collateral objects engaged the attention of Brigadier Campbell,
certain it is that few of the enemy were killed, and that many
thousands safely marched or ran out. The open country, covered
with enclosures and cornfields, enabled the sepoys better to escape
than the British to pursue them. A regiment of Sikhs was sent to
occupy the Moosa Bagh; and now was Lucknow still more fully than
before in the hands of the commander-in-chief.
On the 20th, further measures were taken, by proclamation and
otherwise, to induce the peaceful portion of the inhabitants to return
to their homes. This was desirable in every sense. Until the ordinary
relations of society were re-introduced, anything like civil
government was simply impossible; while, so long as the houses,
deserted by their proper inhabitants, served as hiding-places for
fanatics and budmashes, the streets were never for an instant safe.
Many officers and soldiers were shot by concealed antagonists, long
after the great buildings of the city had been conquered. Moreover,
the Sikhs and Goorkhas were becoming very unruly. The plunder had
acted upon them as an intoxicating indulgence, shaking the steady
obedience which they were wont to exhibit when actively engaged
against the enemy. Even at a time when Sir Colin was planning
which of his generals he could spare, for service elsewhere or for
sick-leave, and which regiments should form new columns for active
service in other districts—even at such a time it was discovered that
bodies of the enemy were lurking in houses near Outram’s head-
quarters, bent upon mischief or revenge; and there was much
musketry-fire necessary before they could be dislodged. The ‘sick-
leave,’ just adverted to, was becoming largely applied for. Many
officers, so gallant and untiring as to be untouched by any suspicion
of their willingness to shirk danger and hard work, gave in; they had
become weakened in body and mind by laborious duties, and
needed repose.
Major Hodson, Commandant of Hodson’s Horse.

The Moulvie, who had held great power within Lucknow, and whose
influence was even now not extinguished, commanded a stronghold
in the very heart of the city. Sir Edward Lugard was requested to
dislodge him on the 21st. This he did after a sharp contest; and
Brigadier W. Campbell, with his cavalry, placed himself in such a
position, that he was enabled to attack the enemy who were put to
flight by Lugard, and to inflict heavy loss on them during a pursuit of
six miles. The conquest of the Moulvie’s stronghold had this useful
effect among others; that it enabled Sir Colin to expedite the
arrangements for the return of such of the inhabitants as were not
too deeply steeped in rebellion to render return expedient. Among
those who fell on this occasion, on the side of the enemy, was
Shirreff-u-Dowlah, the chief-minister of the rebel boy-king, or rather
of his mother the Begum; this man had been in collision with the
Moulvie, each envious of the other’s authority; and there were those
who thought it was by a treacherous blow that he now fell. Even in
this, the last contest within the city, the sappers had to be
employed; for the Moulvie had so intrenched himself, with many
hundred followers, that he could not be dislodged by the force at
first sent against him; the engineers were forced to sap under and
through some surrounding buildings, before the infantry could obtain
command of that in which the Moulvie was lodged.
This was the last day of those complicated scenes of tactics and
fighting which formed collectively the siege of Lucknow, and which
had lasted from the 2d to the 21st of March. Concerning the cavalry
expeditions, during the third week of this period, it is pretty evident
that they had been fruitless in great results. Sir Hope Grant had cut
up a few hundred fugitive rebels in one spot, and intercepted more
in another; Brigadier William Campbell had rendered useful service
both in and beyond the suburbs of the city; but the proofs were not
to be doubted that the mutinied sepoys and rebel volunteers had
safely escaped from the city, not merely by thousands, but by tens
of thousands; and that they still retained a sufficiency of military
organisation to render them annoying and even formidable. When
this news reached England, it damped considerably the pleasure
afforded by the conquest of Lucknow. The nation asked, but asked
without the probability of receiving a reply, whether the enemy had
in this particular foiled a part of the commander-in-chief’s plan; and
whether the governor-general shared the opinions of the
commander concerning the plan of strategy, and the consequences
resulting from it?
The losses suffered by the British army during the operations at
Lucknow, though necessarily considerable, were small in comparison
with those which would have been borne if artillery had not been so
largely used. Sir Colin from the first determined that shells and balls
should do as much of the dread work as possible, clearing away or
breaching the enemy’s defence-works before he sent in his infantry
to close quarters. During the entire series of operations, from the 2d
to the 21st of March, he had 19 officers killed and 48 wounded. The
whole of the generals and brigadiers escaped untouched; and there
were only two officers among the wounded so high in military rank
as lieutenant-colonel. The killed and wounded among the troops
generally were about 1100. The enemy’s loss could hardly have been
less than 4000. One of the deaths most regretted during these
operations was that of Major Hodson; who, as the commander of
‘Hodson’s Horse,’ and as the captor of the King of Delhi, had been
prominently engaged in the Indian wars. It was on the day marked
by the conquest of the Begum Kothee that he fell. Having no
especial duty on that day, and hearing that Brigadier Napier was
busily engaged in engineering operations connected with the attack
on that palace, he rode over to him, and joined in that storming
attack which Sir Colin characterised as ‘the sternest struggle which
occurred during the siege.’ Hodson, while assisting in clearing the
court-yards and buildings near the palace of parties of the enemy
lurking there, was shot by a sepoy. His orderly, a large powerful
Sikh, carried him in his arms to a spot beyond the reach of shot,
whence he was carried in a dooly to Banks’s house, where surgical
aid could be obtained. Some of his own irregular troopers cried over
him like children. The shot had passed through the liver, and he died
after a night of great agony. A spot was chosen for his grave near a
tope of bamboos behind the Martinière. Sir Colin and his staff
attended the funeral, at which the old chief was much affected; he
had highly valued Hodson, and did not allow many hours to elapse
before he wrote a graceful and feeling letter to the widow of the
deceased officer. As soon as possible a telegraphic message was
sent to bring down Captain Daly, the commandant of the famous
corps of Guides; he was every way fitted to command a similar body
of irregular cavalry, ‘Hodson’s Horse.’
No sooner was the city of Lucknow clearly and unequivocally in the
hands of Sir Colin Campbell, than he completely broke up the lately
formidable ‘army of Oude.’ The troops had nothing more immediately
to do at that spot; while their services were urgently needed
elsewhere. With regret did the soldiers leave a place where such
extraordinary gains had fallen to the lot of some among their
number; or, more correctly, this regret endured only until the very
stringent regulations put an effectual stop to all plundering. The
regiments were reorganised into brigades and divisions; new
brigadiers were appointed in lieu of those on ‘sick-leave;’ and a
dispersion of the army commenced.
It is impossible to read Sir Colin Campbell’s mention of Jung
Bahadoor without feeling that he estimated at a small price the
value of the services yielded by the Nepaulese leader. Whether it
was that the arrival of the Goorkha army was delayed beyond the
date when the greatest services might have been rendered, or that
Sir Colin found it embarrassing to issue orders to one who was little
less than a king, it is plain that not much was effected by Jung
Bahadoor during the operations at Lucknow. He came when the
siege was half over; he departed a fortnight afterwards; and
although the commander-in-chief said in a courteous dispatch: ‘I
found the utmost willingness on his part to accede to any desire of
mine during the progress of the siege; and from the first his
Highness was pleased to justify his words that he was happy to be
serving under my command’—although these were the words used,
there was an absence of any reference to special deeds of conquest.
It was a pretty general opinion among the officers that the nine
thousand soldiers of the Nepaulese army were far inferior in military
qualities to those Goorkhas who had for many years formed two or
three regiments in the Bengal army. When the looting in the city
began, Jung Bahadoor’s Goorkhas could scarcely be held in any
control; like the Sikhs, they were wild with oriental excitement, and
Sir Colin was more anxious concerning them than his own European
troops. Viscount Canning, who was in intimate correspondence with
the commander-in-chief through the medium of the electric
telegraph, exchanged opinions with him in terms known only to
themselves; but the announcement made public was to the effect
that the governor-general solicited the aid of the Goorkha troops in
the neighbourhood of Allahabad, and invited Jung Bahadoor to a
personal conference with him at that city. It was during the last
week in March that the Nepaulese allies quitted Lucknow, and
marched off towards the Oude frontier.
Of the troops which remained at Lucknow, after the departure of
some of the brigades, it need only be said in this place that they
began to experience the heat of an Indian equinox, which, though
much less than that of summer, is nevertheless severely felt by
Europeans. A letter from an assistant-surgeon in the division lately
commanded by Brigadier Franks, conveyed a good impression of
camp-troubles at such a time.[150]
When the governor-general wrote the usual thanks and compliments
after the conquest of Lucknow, he adverted very properly to the
previous operations, which, though not conquests in the ordinary
sense of the term, had won so much fame for Inglis, Havelock, Neill,
Outram, and Campbell; and then after mentioning some of the most
obvious facts connected with the siege,[151] praised all those whom
Sir Colin had pointed out as being worthy of praise. Concerning the
proclamation which Lord Canning issued, or proposed to issue, to
the natives of Oude, it will be convenient to defer notice of it to a
future chapter; when attention will be called to the important
debates in the imperial legislature relating to that subject.
Here this chapter may suitably end. It was designed as a medium for
the remarkable episode of the final conquest of Lucknow in the
month of March; and will be best kept free from all topics relating to
other parts of India.
Note.
Lucknow Proclamations.—When Sir Colin Campbell had effectually conquered
Lucknow, and had gathered information concerning the proceedings of the rebels
since the preceding month of November, it was found that no means had been left
untried to madden the populace into a death-struggle with the British. Among
other methods, printed proclamations were posted up in all the police stations, not
only in Lucknow, but in many other parts of Oude.
One of these proclamations, addressed to the Mohammedans, ran thus:
‘God says in the Koran: “Do not enter into the friendship of Jews and Christians;
those who are their friends are of them—that is, the friends of Christians are
Christians, and friends of Jews are Jews. God never shews his way to infidels.”
‘By this it is evident that to befriend Christians, is irreligious. Those who are their
friends are not Mohammedans; therefore all the Mohammedan fraternity should
with all their hearts be deadly enemies to the Christians, and never befriend them
in any way; otherwise, all will lose their religion, and become infidels.
‘Some people, weak in faith and worldly, think that if they offend the Christians,
they will fall their victims when their rule is re-established. God says of these
people: “Look in the hearts of these unbelievers, who are anxious to seek the
friendship of Christians through fear of receiving injury,” to remove their doubts
and assure their wavering mind. It is also said that “God will shortly give us
victory, or will do something by which our enemies will be ashamed of
themselves.” The Mussulmans should therefore always hope, and never believe
that the Christians will be victorious and injure them; but, on the contrary, should
hope to gain the victory and destroy all Christians.
‘If all the Mohammedans join and remain firm to their faith, they would no doubt
gain victory over the Christians, because God says that the victory is due to the
faithful from Him; but if they become cowards and infirm to their religion, and do
not sacrifice their private interest for the public good, the Europeans will be
victorious, and, having subdued the Mohammedans, they will disarm, hang, shoot,
or blow them away, seize upon their women and children, disgrace, dishonour, and
christianise them, dig up their houses and carry off their property; they will also
burn religious and sacred books, destroy the musjids, and efface the name of
Islam from the world.
‘If the Mohammedans have any shame, they should all join and prepare
themselves to kill the Christians without minding any one who says to the
contrary; they should also know that no one dies before his time, and when the
time comes, nothing can save them. Thousands of men are carried off by cholera
and other pestilence; but it is not known whether they die in their senses, and be
faithful to their own religion.
‘To be killed in a war against Christians is a proof of obtaining martyrdom. All good
Mohammedans pray for such a death; therefore, every one should sacrifice his life
for such a reward. Every one is to die assuredly, and those Mohammedans who
would spare themselves now will be sorry on their death for their neglect.
‘As it is the duty of all men and women to oppose, kill, and expel the Europeans
for deeds committed by them at Delhi, Jhujur, Rewaree, and the Doab, all the
Mohammedans should discharge their duty with a willing heart; if they neglect,
and the Europeans overpower them, they will be disarmed, hung, and treated like
the inhabitants of other unfortunate countries, and will have nothing but regret
and sorrow for their lot. Wherefore this notice is given to warn the public.’
Another proclamation, addressed principally to zemindars and Hindoos in general,
but to Mohammedans also, was couched in the following terms:
‘All the Hindoos and Mohammedans know that man loves four things most: 1, his
religion and caste; 2, his honour; 3, his own and his kinsmen’s lives; 4, his
property. All these four are well protected under native rulers; no one interferes
with any one’s religion; every one enjoys his respectability according to his caste
and wealth. All the respectable people—Syad, Shaikh, Mogul, and Patan, among
Mohammedans; and Brahmins, Chatrees, Bys, and Kaeths, among the Hindoos—
are respected according to their castes. No low-caste people like chumars,
dhanook, and passees, can be equal to and address them disrespectfully. No one’s
life or property is taken unless for some heinous crime.
‘The British are quite against these four things—they want to spoil every one’s
caste, and wish both the Mohammedans and Hindoos to become Christians.
Thousands have turned renegades, and many will become so yet; both the nobles
and low caste are equal in their eyes; they disgrace the nobles in the presence of
the ignoble; they arrest or summon to their courts the gentry, nawabs, and rajahs
at the instance of a chumar, and disgrace them; wherever they go they hang the
respectable people, kill their women and children; their troops dishonour the
women, and dig up and carry off their buried property. They do not kill the
mahajuns, but dishonour their women, and carry off their money. They disarm the
people wherever they go, and when the people are disarmed, they hang, shoot, or
blow them away.
‘In some places, they deceive the landholders by promising them remittance of
revenue, or lessen the amount of their lease; their object is that when their
government is settled, and every one becomes their subject, they can readily,
according to their wish, hang, disgrace, or christianise them. Some of the foolish
landholders have been deceived, but those who are wise and careful do not fall
into their snares.
‘Therefore, all the Hindoos and Mohammedans who wish to save their religion,
honour, life, and property, are warned to join the government forces, and not to be
deceived by the British.
‘The passees (low-caste servants) should also know that the chowkeedaree (office
of watchmen) is their hereditary right, but the British appoint burkundauzes in
their posts, and deprive them of their rights; they should therefore kill and plunder
the British and their followers, and annoy them by committing robbery and thefts
in their camp.’

Hindoo Metallic Ornaments.

a Women’s Earrings. b Parsee Women’s Neck-ring. c


Women’s Nose-rings. d Women’s Forehead Ornament.
f Men’s Earrings. g Women’s Anklets. h Women’s
Armlets. i Women’s Toe-rings. k Women’s Finger-rings.
l Women’s Necklace. m Men’s Necklace.
141.
The plans of Lucknow at pp. 321 and 362 will convey an idea
of the situation of the city relatively to the river.

142.

23d Fusiliers.
79th Highlanders.
Rifle Brigade, two battalions.
1st Bengal Europeans.
3d Punjaub infantry.
2d Dragoon Guards.
9th Lancers.
1st, 2d, and 5th Punjaub cavalry, detachment.
D’Aguilar’s troop, horse-artillery.
Remington’s troop, royal artillery.
M’Kinnon’s troop, royal artillery.
Gibbon’s light field-battery.
Middleton’s light field-battery.
Head-quarters, field-artillery brigade.

143.
Mr Russell, all day on the 6th and 7th, was watching the
proceedings from a position such as has seldom before been
occupied by a newspaper writer. He was on the roof of the Dil
Koosha, taking his chance of such shots as came from the
Martinière, and viewing Outram’s marchings and fightings by
means of a telescope. Sometimes his resolution was nearly
baffled by heat and dust. ‘The wind was all but intolerable—
very hot and very high, and surcharged with dust. I had a little
camp-table and chair placed on the top of the building, and
tried to write; but the heat and the dust were intolerable. I
tried to look out, but the glasses were filled with dust; a fog
would be just as good a medium.’
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like