BUY THIS BOOK
Add to Cart

Print Book $34.95


Safari Books Online

What is this?

Add to UK Cart

Print Book £24.95

What is this?

Looking to Reprint this content?

Learning Cocoa with Objective-C
Learning Cocoa with Objective-C, Second Edition

By James Duncan Davidson, Apple Computer, Inc.
Price: $34.95 USD
£24.95 GBP

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: Introduction to Cocoa
Cocoa provides a rich layer of functionality on which you can build applications. Its comprehensive object-oriented API complements a large number of technologies that Mac OS X provides. Some of these technologies are inherited from the NeXTSTEP operating system. Others are based on the BSD Unix heritage of Mac OS X's core. Still others come from the original Macintosh environment and have been updated to work with a modern operating system. In many cases, you take advantage of these underlying technologies transparently, and you get the use of them essentially "for free." In some cases, you might use these technologies directly, but because of the way Cocoa is structured, they are a simple and direct API call away.
This chapter provides an overview of the Mac OS X programming environment and Cocoa's place in it. You will then learn about the two frameworks—Foundation and Application Kit (or AppKit)—that make up the Cocoa API, as well as the functionality that they provide.
Mac OS X provides five principal application environments:
Carbon
A set of procedural APIs for working with Mac OS X. These interfaces were initially derived from the earlier Mac OS Toolbox APIs and modified to work with Mac OS X's protected memory environment and preemptive task scheduling. As a transitional API, Carbon gives developers a clear way to migrate legacy applications to Mac OS X without requiring a total rewrite. Adobe Photoshop 7.0 and Microsoft Office v. X are both examples of "Carbonized" applications. For more information on Carbon, see /Developer/Documentation/Carbon or Learning Carbon (O'Reilly).
Cocoa
A set of object-oriented APIs derived from NeXT's operating-system technologies that take advantage of many features from Carbon. Programming with the Cocoa API is the focus of this book. Many applications that ship with Mac OS X, such as Mail and Stickies, are written in Cocoa. In addition, many of Apple's latest applications, such as iPhoto, iChat, and iDVD2, are built on top of Cocoa.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Mac OS X Programming Environment
Mac OS X provides five principal application environments:
Carbon
A set of procedural APIs for working with Mac OS X. These interfaces were initially derived from the earlier Mac OS Toolbox APIs and modified to work with Mac OS X's protected memory environment and preemptive task scheduling. As a transitional API, Carbon gives developers a clear way to migrate legacy applications to Mac OS X without requiring a total rewrite. Adobe Photoshop 7.0 and Microsoft Office v. X are both examples of "Carbonized" applications. For more information on Carbon, see /Developer/Documentation/Carbon or Learning Carbon (O'Reilly).
Cocoa
A set of object-oriented APIs derived from NeXT's operating-system technologies that take advantage of many features from Carbon. Programming with the Cocoa API is the focus of this book. Many applications that ship with Mac OS X, such as Mail and Stickies, are written in Cocoa. In addition, many of Apple's latest applications, such as iPhoto, iChat, and iDVD2, are built on top of Cocoa.
Java
A robust and fast virtual-machine environment for running applications developed using the Java Development Kit. Java applications are typically very portable and can run unchanged, without recompilation, on many different computing environments.
BSD Unix
The BSD layer of Mac OS X that provides a rich, robust, and mature set of tools and system calls. The standard BSD tools, utilities, APIs, and functions are available to applications. A command-line environment also exists as part of this layer.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Cocoa Defined
Cocoa is an advanced object-oriented framework for building applications that run on Apple's Mac OS X. It is an integrated set of shared object libraries, a runtime system, and a development environment. Cocoa provides most of the infrastructure that graphical user applications typically need and insulates those applications from the internal workings of the core operating system.
Think of Cocoa as a layer of objects acting as both mediator and facilitator between programs that you build and the operating system. These objects span the spectrum from simple wrappers for basic types, such as strings and arrays, to complex functionality, such as distributed computing and advanced imaging. They are designed to make it easy to create a graphical user interface (GUI) application and are based on a sophisticated infrastructure that simplifies the programming task.
Cocoa-based applications are not just limited to using the features in the Cocoa frameworks. They can also use all of the functionality of the other frameworks that are part of Mac OS X, such as Quartz, QuickTime, OpenGL, ColorSync, and many others. And since Mac OS X is built atop Darwin, a solid BSD-based system, Cocoa-based applications can use all of the core Unix system functions and get as close to the underlying filesystem, network services, and devices as they need to.
Cocoa has actually been around a long time—almost as long as the Macintosh itself. That is because it is, to a large extent, based on OpenStep, which was introduced to the world as NeXTSTEP in 1987, along with the elegant NeXT cube. At the time, the goal of NeXTSTEP was to, as only Steve Jobs could say, "create the next insanely great thing." It evolved through many releases, was adopted by many companies as their development and deployment environment of choice, and received glowing reviews in the press. It was, and continues to be, solid technology based on a design that was years ahead of anything else in the market.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Cocoa Frameworks
Cocoa is composed of two object-oriented frameworks: Foundation (not to be confused with Core Foundation) and Application Kit. These layers fit into the system as shown in Figure 1-2.
Figure 1-2: The Cocoa frameworks in the system
The classes in Cocoa's Foundation framework provide objects and functionality that are the basis, or "foundation," of Cocoa and that do not have an impact on the user interface. The AppKit classes build on the Foundation classes and furnish the objects and behavior that your users see in the user interface, such as windows and buttons; the classes also handle things like mouse clicks and keystrokes. One way to think of the difference in the frameworks is that Cocoa's Foundation classes provide functionality that operates under the surface of the application, while the AppKit classes provide the functionality for the user interface that the user sees.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Languages
You can build Cocoa applications in three languages: Objective-C, Java, and AppleScript. Objective-C was the original language in which NeXTSTEP was developed and is the "native language" of Cocoa. It is the language that we will work with throughout this book. During the early development of Mac OS X (when it was still known as Rhapsody), a layer of functionality—known as the Java Bridge—was added to Cocoa, allowing the API to be used with Java. Support has been recently added for AppleScript in the form of AppleScript Studio, which allows AppleScripters to hook into the Cocoa frameworks to provide a comprehensive Aqua-based GUI to their applications.
The brainchild of Brad Cox, Objective-C is a very simple language. It is a superset of ANSI C with a few syntax and runtime extensions that make object-oriented programming possible. It started out as just a C preprocessor and a library, but over time developed into a complete runtime system, allowing a high degree of dynamism and yielding large benefits. Objective-C's syntax is uncomplicated, adding only a small number of types, preprocessor directives, and compiler directives to the C language, as well as defining a handful of conventions used to interact with the runtime system effectively.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Foundation Framework
The Foundation framework is a set of over 80 classes and functions that define a layer of base functionality for Cocoa applications. In addition, the Foundation framework provides several paradigms that define consistent conventions for memory management and traversing collections of objects. These conventions allow you to code more efficiently and effectively by using the same mechanisms with various kinds of objects. Two examples of these conventions are standard policies for object ownership (who is responsible for disposing of objects) and a set of standard abstract classes that enumerate over collections. Figure 1-3 shows the major groupings into which the Foundation classes fall.
Figure 1-3: Features of the Foundation framework
The Foundation framework includes the following:
  • The root object class, NSObject
  • Classes representing basic data types, such as strings and byte arrays
  • Collection classes for storing other objects
  • Classes representing system information and services
The Foundation framework provides many basic types, including strings and numbers. It also furnishes several classes whose purpose is to hold other objects—the array and dictionary collections classes. You'll learn more about these data types—and how to use them—throughout the chapters in this book, starting in Chapter 4.
Strings
Cocoa's string class, NSString, supplants the familiar C programming data type char * to represent character string data. String objects contain Unicode characters rather than the narrow range of characters afforded by the ASCII character set, allowing them to contain characters in any language, including Chinese, Arabic, and Hebrew. The string classes provide an API to create both mutable and immutable strings and to perform string operations such as substring searching, string comparison, and concatenation.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Application Kit Framework
The Application Kit framework (or AppKit, as it's more commonly called) contains a set of over 120 classes and related functions that are needed to implement graphical, event-driven user interfaces. These classes implement the functionality needed to efficiently draw the user interface to the screen, communicate with video cards and screen buffers, and handle events from the keyboard and mouse.
Learning the many classes in the AppKit may seem daunting at first. However, you won't need to learn every feature of every class. Most of the AppKit classes are support classes that work behind the scenes helping other classes operate and with which you will not have to interact directly. Figure 1-4 shows how AppKit classes are grouped and related.
Figure 1-4: The Application Kit framework's features
The user interface is how users interact with your application. You can create and manage windows, dialog boxes, pop-up lists, and other controls. We'll cover these topics in depth starting in Chapter 6.
Windows
The two principle functions of a window are to provide an area in which views can be placed and to accept and distribute to the appropriate view events that the user creates through actions with the mouse and keyboard. Windows can be resized, minimized to the Dock, and closed. Each of these actions generates events that can be monitored by a program.
Views
A view is an abstract representation for all objects displayed in a window. Views provide the structure for drawing, printing, and handling events. Views are arranged within a window in a nested hierarchy of subviews.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Cocoa Development Tools
Getting started with Cocoa requires that quite a few concepts be presented at once. Since a book is a linear construction, we have had to make some choices as to what pieces to present first. In order to get your hands dirty using the tools, we chose to introduce Apple's Development Tools first as a way to get you started in building your first Cocoa application. You'll see some concepts here that will be glossed over. Don't worry; we will revisit them as we go. For now, though, just go along for the ride and try not to pay too much attention to the details we're saving for later.
When Apple released Mac OS X, they made a really great decision. They decided to provide their development tools to every Mac user for free. These tools allow development of Carbon- and Cocoa-based applications, system libraries, BSD command-line utilities, hardware device drivers, and even kernel extensions. We'll be focusing on two of these tools to develop Cocoa-based applications throughout the book: Project Builder for editing, compiling, and debugging source code, and Interface Builder for laying out the graphical user interface (GUI) components for the application.
By default, the tools aren't installed, as most users won't use them and probably want the almost 500 MB of disk space for something else. But developers can easily find them and install them from a variety of sources. And, since they are free, any user who wants to try developing software can do so by investing only the time it takes to learn.
You can quickly check to see if you have the Developer Tools installed. If you have a /Developer/Applications folder on your hard drive, as shown in Figure 2-1, you are ready to go. If not, you'll need to install the tools from either the Developer Tools CD that came with your copy of Mac OS X or from a disk image you can download from the Apple Developer Connection (ADC) site.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installing the Developer Tools
When Apple released Mac OS X, they made a really great decision. They decided to provide their development tools to every Mac user for free. These tools allow development of Carbon- and Cocoa-based applications, system libraries, BSD command-line utilities, hardware device drivers, and even kernel extensions. We'll be focusing on two of these tools to develop Cocoa-based applications throughout the book: Project Builder for editing, compiling, and debugging source code, and Interface Builder for laying out the graphical user interface (GUI) components for the application.
By default, the tools aren't installed, as most users won't use them and probably want the almost 500 MB of disk space for something else. But developers can easily find them and install them from a variety of sources. And, since they are free, any user who wants to try developing software can do so by investing only the time it takes to learn.
You can quickly check to see if you have the Developer Tools installed. If you have a /Developer/Applications folder on your hard drive, as shown in Figure 2-1, you are ready to go. If not, you'll need to install the tools from either the Developer Tools CD that came with your copy of Mac OS X or from a disk image you can download from the Apple Developer Connection (ADC) site.
Figure 2-1: Apple's development tools in the filesystem
A CD containing the Developer Tools comes with every boxed set of Mac OS X (including Mac OS X Server). To install the tools, simply find the CD (it's the gray one), put it into your CD-ROM drive, and double-click the Developer.mpkg file that appears in a Finder window, as shown in Figure 2-2.
Figure 2-2: The Developer Tools installation file
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Interface Builder
Interface Builder is where you create the graphical user interfaces (GUIs) for your applications. Instead of typing code by hand to lay out the interface components, you drag objects from palettes and drop them onto the GUI you are creating. Objects can be connected to one another and with instances of classes that you provide as part of your application.
Interface Builder generates nib files that are an archive of object instances and are packaged up with your built application. Unlike the product of many user interface-building systems, nib files are not generated code—they are true archived (also known as "freeze-dried") objects consisting of related user interface objects and supporting resources, along with information about how the objects are related. The objects in the nib file are created and manipulated using Interface Builder's graphical tools.
Interface Builder's standard palettes hold an assortment of AppKit components. Other palettes can include Cocoa objects from other frameworks, third-party objects, and custom-compiled objects.
To introduce you to Interface Builder, we are going to create a program that says "Hello, World" in a window on the screen instead of as a text message in a Terminal window. To begin, we need to make a new project of a type different than our previous Hello World application. Choose New Project from the File menu. Project Builder then displays the New Project Assistant. This time, create a project of type Cocoa Application, as shown in Figure 2-14.
Figure 2-14: Creating a Cocoa application
This will create a project that is set up as a simple Cocoa application. Go ahead and create the project, giving it the name Hello World
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Other Tools
In addition to Project Builder and Interface Builder, there are other applications that you can use in the Cocoa development process. Development tools that feature a GUI are listed in Table 2-1. Except where noted, these applications are installed in the /Developer/Applications folder.
Table 2-1: Other development tools
Name
Description
FileMerge
Visually compares the contents of two files or two directories. You can use FileMerge to determine the differences between versions of the same source-code file or between two project directories. You can also use it to merge changes.
icns Browser
Displays the entire contents of Mac OS X icon files.
IconComposer
Creates Mac OS X icons from source art.
IORegistryExplorer
Provides a hierarchical display of the system I/O registry.
MallocDebug
Measures the dynamic-memory usage of applications, finds memory leaks, analyzes all allocated memory in an application, and measures the memory allocated since a given time.
ObjectAlloc
Tracks and displays all Cocoa and Core Foundation object allocations for a running application. ObjectAlloc allows you to view the list of objects, as well as the call stack that resulted in each allocation.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Exercises
  1. Locate the Project Builder and Interface Builder applications, and put them into the Dock.
  2. Locate the developer documentation, and place a shortcut to it in your Dock or in your browser.
  3. Watch the "Accessing API Documentation in Project Builder" movie at http://developer.apple.com/techpubs/macosx/DeveloperTools/ProjectBuilderAccess/index.html.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Object-Oriented Programming with Objective-C
Object-oriented programming isn't rocket science, but you can't learn it overnight either. There is a lot of terminology—composed of words like "encapsulation" and "polymorphism" and phrases like "is-a" and "has-a"—that goes with the territory. The concepts behind these terms are not terribly complicated, but they can be hard to explain. Like most useful fields of study, you must work with it a while before it all clicks together in your mind. As each concept becomes clear, you will gain a deeper understanding of the subject. That said, you don't have to understand everything about object-oriented programming on the first pass to make good use of the concepts.
In this chapter, we present the object-oriented concepts that matter most when working with Cocoa, along with quite a bit of hands-on practice using those concepts. If this is the first time you've approached object-oriented programming, read carefully, but don't worry if you don't get everything at first. Just remember to flip back to this part of the book later if something didn't sink in. If you already know a bit about object-oriented programming, then you should treat this as a refresher and see how Objective-C's implementation of the object-oriented concepts with which you are familiar works.
Procedural programming divides the programming problem into two parts: data and operations on that data. Because all of the functionality of a procedural program works on the same set of data, the programmer must be very careful to manipulate the data of a program in such a way that the rest of the program can work correctly. He must be aware of the entire program at a low level of abstraction so as not to introduce errors. As a procedural program grows in size, the network of interaction between procedures and data becomes increasingly complex and hard to manage.
Object-oriented programming (OOP), first developed in the 1960s, restructures the programming problem to allow for a higher level of abstraction. It groups operations and data into modular units called
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introducing Objects
Procedural programming divides the programming problem into two parts: data and operations on that data. Because all of the functionality of a procedural program works on the same set of data, the programmer must be very careful to manipulate the data of a program in such a way that the rest of the program can work correctly. He must be aware of the entire program at a low level of abstraction so as not to introduce errors. As a procedural program grows in size, the network of interaction between procedures and data becomes increasingly complex and hard to manage.
Object-oriented programming (OOP), first developed in the 1960s, restructures the programming problem to allow for a higher level of abstraction. It groups operations and data into modular units called objects. These objects can be combined into structured networks to form a complete program, similar to how the pieces in a puzzle fit together to create a picture. In contrast to procedural programming's focus on the interaction between data and functions, the design of objects and the interactions between those objects become the primary elements of object-oriented program design.
By breaking down complex software projects into small, self-contained, and modular units, object orientation ensures that changes to one part of a software project will not adversely affect other portions of the software. Object orientation also aids software reuse. Once functionality is created in one program, it can easily be reused in other programs.
Programming with objects is quite like working with real-world objects. Take an iPod, for example. It embodies both state and behavior. When you operate it, you don't necessarily care how it works, as long as it works in the way that you expect. As long as your iPod plays music when you tell it to and synchronizes your music collection with iTunes when you plug it into your computer, you're happy. Object-oriented programming brings this same level of abstraction to programming and helps remove some of the impediments to building larger systems. To enjoy listening to music, you don't have to know that iTunes and your iPod use the MP3 format; you just put a CD into your computer and import the music into your collection. iTunes and your iPod work together to download the music from your computer when you plug in the iPod. Figure 3-1 shows these components working together.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating and Using Objects
Now that we've introduced a few object-oriented concepts, we are going to dive into some simple code exercises to show how to apply this knowledge. The following steps will guide you:
  1. In Project Builder, create a new Foundation tool (File New Project Tool Foundation Tool) project named "objects", and save it in your ~/LearningCocoa folder.
  2. Next, modify the main.m file, located in the "Source" group, so that it looks like Example 3-1. The Foundation tool project template automatically generates some of this code. The lines that you need to add are shown in boldface type.
    Example 3-1. Creating objects
    int main (int argc, const char * argv[]) {
        NSAutoReleasepool *pool = [[NSAutoreleasepool alloc] init];
    
        NSObject * object;                                               // a
                                object = [NSObject alloc];                                       // b
                                object = [object init];                                          // c
                                NSLog(@"Created object: %@", object);                            // d
    
        [pool release];
        return 0;
    }
    Here's what the code that we added does:
    1. Declares a variable named object of type NSObject. You should recognize this as a regular C pointer.
    2. Creates a new object of type NSObject and assigns it to the object variable. The alloc method reserves (or allocates) memory space for the object and returns a pointer to that space. We'll explain more about methods in just a bit.
    3. Before an object is used in any way, it must be initialized. This init call initializes the object so it can be used. The init
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Methods and Messages
In our discussion about objects so far, we've been using (and promised to explain) the term method . Methods are structured like C functions and can be thought of as procedures; but, instead of being global in nature, they are procedures associated with and implemented by the object's class.
There are two kinds of methods: class methods and instance methods . Class methods are scoped to the class itself and cannot be called on instances of the class. The alloc method is an example of a class method. Instance methods, on the other hand, are scoped to object instances. The init method is an example of an instance method that is called on an instance of an object returned by the alloc method.
To call a method, send an object a message telling it to apply a method. All those square brackets that you have seen in the code are message expressions that result in methods being called. Figure 3-5 shows the various parts of a basic message.
Figure 3-5: Objective-C message expression
In this figure, the message is the expression enclosed in square brackets to the right of the assignment operator (equals sign). The message consists of an object, known as a receiver , and the name of a method to call on that object. In this case, the object is the NSObject class, and the method to be called is the alloc method. In response to receiving this message, the NSObject class returns a new instance of the class that will be assigned to the variable anObject.
The message in Figure 3-5 calls a method that doesn't take any arguments. Like procedures, methods can receive multiple arguments. In Objective-C, every message argument is identified with a label (a colon-terminated keyword), which is considered part of the method name. Figure 3-6 shows a message with a single argument.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Objective-C-Defined Types
So far, we've talked about a few of Objective-C's built-in types, such as SEL. Before we continue, Table 3-1 lists the set of Objective-C-defined types.
Table 3-1: Objective-C-defined types
Type
Definition
id
An object reference (a pointer to its data structure)
Class
A class object reference (a pointer to its data structure)
SEL
A selector (a compiler-assigned code that identifies a method name)
IMP
A pointer to a method implementation that returns an id
BOOL
A Boolean value, either YES or NO
nil
A null object pointer, (id)0
Nil
A null class pointer, (Class)0
The id type can be used to type any kind of object, class, or instance. In addition, class names can be used as type names to type instances of a class statically. A statically typed instance is declared as a pointer to an instance of its class or to an instance of any class from which it inherits.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating New Classes
When you want to create a new kind of object, you define a new class. A class is defined in two files. One file, the header file (.h), declares the variables and methods that can be invoked by messages sent to objects belonging to the class. The other file is the implementation file (.m), which actually implements the methods declared by the header file, as well as the private implementation details of the class. The interface defined in the header file is public. The implementation is private and can be changed without affecting the interface or the way the class is used.
To show how to create a new class, we will model songs that would go into an MP3 player. Don't get too scared yet; we're not actually going to write the MP3 player itself.
  1. To get started, create a new Foundation Tool in Project Builder (File New Project Tools Foundation Tool) named "songs", and save it in your ~/LearningCocoa folder.
  2. Define a header for our song class. Choose File New File, then select Objective-C class as the file type, as shown in Figure 3-11.
    Figure 3-11: New File Assistant
  3. Name the file Song.m, as shown in Figure 3-12. Make sure that the Also create "Song.h" checkbox is clicked. This creates the header file for the application's interface.
Figure 3-12: New Objective-C class Assistant
Be careful not to confuse this use of the word interface with the term Graphical User Interface
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Overriding Methods
A subclass can not only add new methods to the ones it inherits from a superclass; it can also replace, or override, an inherited method with a new implementation. No special syntax is required; just reimplement the method in the subclass's implementation file.
Overriding methods doesn't alter the set of messages that an object can receive. It alters the method implementation that will be used to respond to those messages. This ability for each class to implement its own version of a method is known as polymorphism .
  1. Edit the Song.m file as shown in Example 3-7 to add the description method.
    Example 3-7. Adding the description method
    #import "Song.h"
    
    @implementation Song
    
    - (NSString *)name
    {
        return name;
    }
    
    - (void)setName:(NSString *)newName                                 
    {
        [newName retain];                                               
        [name release];                                               
        name = newName;                                                 
    }
    
    - (NSString *)artist
    {
        return artist;
    }
    
    - (void)setArtist:(NSString *)newArtist                            
    {
        [newArtist retain];                                            
        [artist release];                                           
        artist = newArtist;                               
    }
    
    - (NSString *)description                           // a
                            {
                                return [self name];                             // b
                            }
    
    @end
    The code we added performs the following tasks:
    1. Declares the description method that overrides the method by the same name in the NSObject class. We don't need to declare this method in the Song.h interface file, as it is already part of the interface declared by NSObject.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Other Concepts
There are some other concepts in object-oriented programming and Objective-C that we haven't explored in depth in this chapter. Before you learn too much about these new concepts, you'll want to practice quite a bit with the concepts that you've already learned. We're telling you about these other concepts now so that when you come to them, you won't be surprised.
Categories
You can add methods to a class by declaring them in an interface file under a category name and defining them in an implementation file under the same name. The category name indicates that the methods are additions to a class declared elsewhere, not to a new class.
Protocols
Class and category interfaces declare methods that are associated with a particular class—methods that the class implements. Informal and formal protocols, on the other hand, declare methods that are not associated with a class, but which any class—and perhaps many classes—might implement. We'll talk more about protocols in Chapter 9.
Introspection
An object, even one typed as id, can reveal its class and divulge other characteristics at runtime. Several introspection methods, such as isMemberOfClass: and isKindOfClass:, allow you to ascertain the inheritance relationships of an object and the methods to which it responds.
Remember, you can find out much more information about Objective-C and object-oriented programming in the developer documentation installed on your hard drive along with the Developer Tools (/Developer/Documentation/Cocoa/ObjectiveC ).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Exercises
  1. Use the resources in Appendix C, and read the documentation for NSObject and NSString.
  2. Read the documentation for the NSLog function.
  3. Investigate the isa and self variables by having the designated initializer of the Song class print a description of the class.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: The Cocoa Foundation Kit
Now that we have filled your head with lots of theory about object-oriented programming, we'll look into some of the essential parts of Cocoa's Foundation framework. In this chapter we cover strings, collections, and memory management. Once you have a firm grasp on these topics, you'll be ready for the raison d'être of Cocoa: GUI programming.
The nature of these topics doesn't lend itself to a nifty, all-inclusive code example that shows everything in action at once. So, instead of contriving a single, awkward example, we're just going to work through a set of simple code samples to illustrate the concepts presented. We'll also augment the use of these samples with some usage of the debugger.
So far, we have worked with strings using the @" . . . " construct in various method and function calls. This construct is convenient when working with strings. When interpreted by the compiler, it is translated into an NSString object that is based on the 7-bit ASCII-encoded string (also known as a "C string") between the quotes. For example, the statement:
NSString * lush = @"Lush";
is functionally equivalent to:
NSString * lush = [[NSString alloc] initWithCString:"Lush"];
NSString objects are not limited to the ASCII character set; they can handle any character contained in the Unicode character set, allowing most of the world's living languages to be represented. Unicode is a 16-bit-wide character set, but can be represented in 8-bits using the UTF-8 encoding.
NSString provides several methods that are handy when working with strings. A few of these methods are as follows:
- (int)length
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Strings
So far, we have worked with strings using the @" . . . " construct in various method and function calls. This construct is convenient when working with strings. When interpreted by the compiler, it is translated into an NSString object that is based on the 7-bit ASCII-encoded string (also known as a "C string") between the quotes. For example, the statement:
NSString * lush = @"Lush";
is functionally equivalent to:
NSString * lush = [[NSString alloc] initWithCString:"Lush"];
NSString objects are not limited to the ASCII character set; they can handle any character contained in the Unicode character set, allowing most of the world's living languages to be represented. Unicode is a 16-bit-wide character set, but can be represented in 8-bits using the UTF-8 encoding.
NSString provides several methods that are handy when working with strings. A few of these methods are as follows:
- (int)length
Returns the number of Unicode characters in the string object upon which it is called.
- (const char *)cString
Returns a representation of the string as a C string in the default encoding. This method is helpful when you need to operate with C-based functions, such as those found in traditional Unix system calls.
It's important to note that since C strings are 7-bit, and the NSString class can handle the full Unicode character set, not all NSString objects can be represented as C strings.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Collections
Cocoa provides several classes in the Foundation Kit whose purpose is to hold and organize instances of other classes. These are called the collection classes. There are three primary flavors of collections in Cocoa: arrays , sets , and dictionaries . These classes, shown in Figure 4-3, are extremely useful in Cocoa application development, and their influence can be found throughout the Cocoa class libraries.
Figure 4-3: Cocoa collection classes
Collection classes, like strings, come in two forms: mutable and immutable . Immutable classes allow you to add items when the collection is created, but no further changes are allowed. On the other hand, mutable classes allow you to add and remove objects programmatically after the collection is created.
Much of the power of collection classes comes from their ability to manipulate the objects they contain. Not every collection object can perform every function, but in general, collection objects can do the following:
  • Derive their initial contents from files and URLs, as well as other collections of objects
  • Add, remove, locate, and sort contents
  • Compare their contents with other collection objects
  • Enumerate over their contents
  • Send a message to the objects that they contain
  • Archive their contents to a file on disk and retrieve it later
Arrays—instances of the NSArray class—are ordered collections of objects indexed by integers. Like C-based arrays, the first object in an array is located at index 0. Unlike C- and Java-based arrays whose size is set when they are created, Cocoa mutable array objects can grow as needed to accommodate inserted objects.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Memory Management
Content preview·Buy PDF of this chapter|