| < Previous PageNext Page > |
Let’s begin with a simple command-line program. Given a series of arbitrary words as arguments, the program removes redundant occurrences, sorts the remaining list of words in alphabetical order, and prints the list to standard output. Listing 2-1 shows a typical execution of this program.
Listing 2-1 Output from a simple Cocoa tool
localhost> SimpleCocoaTool a z c a l q m z |
a |
c |
l |
m |
q |
z |
Listing 2-2 shows the code for an Objective-C version of this program.
Listing 2-2 Cocoa code for a uniquing and sorting tool
#import <Foundation/Foundation.h> |
int main (int argc, const char * argv[]) { |
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; |
NSArray *args = [[NSProcessInfo processInfo] arguments]; |
NSCountedSet *cset = [[NSCountedSet alloc] initWithArray:args]; |
NSArray *sorted_args = [[cset allObjects] |
sortedArrayUsingSelector:@selector(compare:)]; |
NSEnumerator *enm = [sorted_args objectEnumerator]; |
id word; |
while (word = [enm nextObject]) { |
printf("%s\n", [word UTF8String]); |
} |
[cset release]; |
[pool release]; |
return 0; |
} |
This code creates and uses several objects: an autorelease pool for memory management, collection objects (arrays and a set) for “uniquing” and sorting the specified words, and an enumerator object for iterating through the elements in the final array and printing them to standard output.
The first thing you probably notice about this code is that it is short, perhaps much shorter than a typical ANSI C version of the same program. Although much of this code might look strange to you, many of its elements are familiar ANSI C. These include assignment operators, control-flow statements (while), calls to C-library routines (printf), primitive scalar types, and so on. Objective-C obviously has ANSI C underpinnings.
The rest of this chapter examines the Objective-C elements of this code, using them as examples in discussions on subjects ranging from the mechanics of message-sending to the techniques of memory management. If you haven’t seen Objective-C code before, the code in the example might seem formidably convoluted and obscure, but that impression will melt away soon. Objective-C is actually a simple, elegant programming language that is easy to learn and intuitive to program with.
| < Previous PageNext Page > |
© 2006 Apple Computer, Inc. All Rights Reserved. (Last updated: 2006-12-20)
|