Using Existing Classes
If it isn’t running, start Xcode. Close any projects that you were working on. Under the File menu, choose New -> New Project.... When the panel pops up, choose to create a Command Line Tool (Figure 3.1).
Figure 3.1. Choose Project Type
A command-line tool has no graphical user interface and typically runs on the command line or in the background as a daemon. Unlike in an application project, you will always alter the main function of a command-line tool.
Name the project lottery (Figure 3.2). Unlike the names of applications, most tool names are lowercase. Set the Type to Foundation.
Figure 3.2. Name Project
When the new project appears, select main.m in the lottery group. Edit main.m to look like this:
#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { @autoreleasepool { NSMutableArray *array; array = [[NSMutableArray alloc] init]; int i; for (i = 0; i < 10; i++) { NSNumber *newNumber = [[NSNumber alloc] initWithInt:(i * 3)]; [array addObject:newNumber]; } for ( i = 0; i < 10; i++) { NSNumber *numberToPrint = [array objectAtIndex:i]; NSLog(@"The number at index %d is %@", i, numberToPrint); } } return 0; }
Here is the play-by-play for the code:
#import <Foundation/Foundation.h>
You are including the headers for all the classes in the Foundation framework. The headers are precompiled, so this approach is not as computationally intensive as it sounds.
int main (int argc, const char *argv[])
The main function is declared just as it would be in any Unix C program.
@autoreleasepool {
This code defines an autorelease pool for the code enclosed by the braces. We will discuss the importance of autorelease pools in the next chapter.
NSMutableArray *array;
One variable is declared here: array is a pointer to an instance of NSMutableArray. Note that no array exists yet. You have simply declared a pointer that will refer to the array once it is created.
array = [[NSMutableArray alloc] init];
Here, you are creating the instance of NSMutableArray and making the array variable point to it.
for (i = 0; i < 10; i++) { NSNumber *newNumber = [[NSNumber alloc] initWithInt:(i*3)]; [array addObject:newNumber]; }
Inside the for loop, you have created a local variable called newNumber and set it to point to a new instance of NSNumber. Then you have added that object to the array.
The array does not make copies of the NSNumber objects. Instead, it simply keeps a list of pointers to the NSNumber objects. Objective-C programmers make very few copies of objects, because it is seldom necessary.
for ( i = 0; i < 10; i++) { NSNumber *numberToPrint = [array objectAtIndex:i]; NSLog(@"The number at index %d is %@", i, numberToPrint); }
Here, you are printing the contents of the array to the console. NSLog is a function much like the C function printf(); it takes a format string and a comma-separated list of variables to be substituted into the format string. When displaying the string, NSLog prefixes the generated string with the name of the application and a time stamp.
In printf, for example, you would use %x to display an integer in hexadecimal form. With NSLog, we have all the tokens from printf and the token %@ to display an object. The object gets sent the message description, and the string it returns replaces %@ in the string. We will discuss the description method in detail soon.
All the tokens recognized by NSLog() are listed in Table 3.1.
Table 3.1. Possible Tokens in Objective-C Format Strings
Symbol |
Displays |
%@ |
id |
%d, %D, %i |
long |
%u, %U |
unsigned long |
%hi |
short |
%hu |
unsigned short |
%qi |
long long |
%qu |
unsigned long long |
%x, %X |
unsigned long printed as hexadecimal |
%o, %O |
unsigned long printed as octal |
%f, %e, %E, %g, %G |
double |
%c |
unsigned char as ASCII character |
%C |
unichar as Unicode character |
%s |
char * (a null-terminated C string of ASCII characters) |
%S |
unichar * (a null-terminated C string of Unicode characters) |
%p |
void * (an address printed in hexadecimal with a leading 0x) |
%% |
a % character |
Our main() function ends by returning 0, indiciating that no error occurred:
return 0; }
Run the completed command-line tool (Figure 3.3). (If your console doesn’t appear, use the View -> Show Debug Area menu item and ensure that the console, the right half, is enabled.)
Figure 3.3. Completed Execution
Sending Messages to nil
In most object-oriented languages, your program will crash if you send a message to null. In applications written in those languages, you will see many checks for null before sending a message. In Java, for example, you frequently see the following:
if (foo != null) { foo.doThatThingYouDo(); }
In Objective-C, it is okay to send a message to nil. The message is simply discarded, which eliminates the need for these sorts of checks. For example, this code will build and run without an error:
id foo; foo = nil; int bar = [foo count];
This approach is different from how most languages work, but you will get used to it.
You may find yourself asking over and over, “Argg! Why isn’t this method getting called?” Chances are that the pointer you are using, convinced that it is not nil, is in fact nil.
In the preceding example, what is bar set to? Zero. If bar were a pointer, it would be set to nil (zero for pointers). For other types, the value is less predictable.
NSObject, NSArray, NSMutableArray, and NSString
You have now used these standard Cocoa objects: NSObject, NSMutableArray, and NSString. (All classes that come with Cocoa have names with the NS prefix. Classes that you will create will not start with NS.) These classes are all part of the Foundation framework. Figure 3.4 shows an inheritance diagram for these classes.
Figure 3.4. Inheritance Diagram
Let’s go through a few of the commonly used methods on these classes. For a complete listing, you can access the online documentation in Xcode’s Help menu.
NSObject
NSObject is the root of the entire Objective-C class hierarchy. Some commonly used methods on NSObject are described next.
- (id)init
Initializes the receiver after memory for it has been allocated. An init message is generally coupled with an alloc message in the same line of code:
TheClass *newObject = [[TheClass alloc] init];
- (NSString *)description
Returns an NSString that describes the receiver. The debugger’s print object command (“po”) invokes this method. A good description method will often make debugging easier. Also, if you use %@ in a format string, the object that should be substituted in is sent the message description. The value returned by the description method is put into the log string. For example, the line in your main function
NSLog(@"The number at index %d is %@", i, numberToPrint);
is equivalent to
NSLog(@"The number at index %d is %@", i, [numberToPrint description]);
- (BOOL)isEqual:(id)anObject
Returns YES if the receiver and anObject are equal and NO otherwise. You might use it like this:
if ([myObject isEqual:anotherObject]) { NSLog(@"They are equal."); }
But what does equal really mean? In NSObject, this method is defined to return YES if and only if the receiver and anObject are the same object—that is, if both are pointers to the same memory location.
Clearly, this is not always the “equal” that you would hope for, so this method is overridden by many classes to implement a more appropriate idea of equality. For example, NSString overrides the method to compare the characters in the receiver and anObject. If the two strings have the same characters in the same order, they are considered equal.
Thus, if x and y are NSStrings, there is a big difference between these two expressions:
x == y
and
[x isEqual:y]
The first expression compares the two pointers. The second expression compares the characters in the strings. Note, however, that if x and y are instances of a class that has not overridden NSObject’s isEqual: method, the two expressions are equivalent.
NSArray
An NSArray is a list of pointers to other objects. It is indexed by integers. Thus, if there are n objects in the array, the objects are indexed by the integers 0 through n – 1. You cannot put a nil in an NSArray. (This means that there are no “holes” in an NSArray, which may confuse some programmers who are used to Java’s Object[].) NSArray inherits from NSObject.
An NSArray is created with all the objects that will ever be in it. You can neither add nor remove objects from an instance of NSArray. We say that NSArray is immutable. (Its mutable subclass, NSMutableArray, will be discussed next.) Immutability is nice in some cases. Because it is immutable, a horde of objects can share one NSArray without worrying that one object in the horde might change it. NSString and NSNumber are also immutable. Instead of changing a string or number, you will simply create another one with the new value. (In the case of NSString, there is also the class NSMutableString that allows its instances to be altered.)
A single array can hold objects of many different classes. Arrays cannot, however, hold C primitive types, such as int or float.
Here are some commonly used methods implemented by NSArray:
- (unsigned)count
Returns the number of objects currently in the array.
- (id)objectAtIndex:(unsigned)i
Returns the object located at index i. If i is beyond the end of the array, you will get an error at runtime.
- (id)lastObject
Returns the object in the array with the highest index value. If the array is empty, nil is returned.
- (BOOL)containsObject:(id)anObject
Returns YES if anObject is present in the array. This method determines whether an object is present in the array by sending an isEqual: message to each of the array’s objects and passing anObject as the parameter.
- (unsigned)indexOfObject:(id)anObject
Searches the receiver for anObject and returns the lowest index whose corresponding array value is equal to anObject. Objects are considered equal if isEqual: returns YES. If none of the objects in the array are equal to anObject, indexOfObject: returns NSNotFound.
NSMutableArray
NSMutableArray inherits from NSArray but extends it with the ability to add and remove objects. To create a mutable array from an immutable one, use NSArray’s mutableCopy method.
Here are some commonly used methods implemented by NSMutableArray:
- (void)addObject:(id)anObject
Inserts anObject at the end of the receiver. You are not allowed to add nil to the array.
- (void)addObjectsFromArray:(NSArray *)otherArray
Adds the objects contained in otherArray to the end of the receiver’s array of objects.
- (void)insertObject:(id)anObject atIndex:(unsigned)index
Inserts anObject into the receiver at index, which cannot be greater than the number of elements in the array. If index is already occupied, the objects at index and beyond are shifted up one slot to make room. You will get an error if anObject is nil or if index is greater than the number of elements in the array.
- (void)removeAllObjects
Empties the receiver of all its elements.
- (void)removeObject:(id)anObject
Removes all occurrences of anObject in the array. Matches are determined on the basis of anObject’s response to the isEqual: message.
- (void)removeObjectAtIndex:(unsigned)index
Removes the object at index and moves all elements beyond index down one slot to fill the gap. You will get an error if index is beyond the end of the array.
As mentioned earlier, you cannot add nil to an array. Sometimes, you will want to put an object into an array to represent nothingness. The NSNull class exists for exactly this purpose. There is exactly one instance of NSNull, so if you want to put a placeholder for nothing into an array, use NSNull like this:
[myArray addObject:[NSNull null]];
NSString
An NSString is a buffer of Unicode characters. In Cocoa, all manipulations involving character strings are done with NSString. As a convenience, the Objective-C language also supports the @"..." construct to create a string object constant from a 7-bit ASCII encoding:
NSString *temp = @"this is a constant string";
NSString inherits from NSObject. Here are some commonly used methods implemented by NSString:
- (id)initWithFormat:(NSString *)format, ...
Works like sprintf. Here, format is a string containing tokens, such as %d. The additional arguments are substituted for the tokens:
int x = 5; char *y = "abc"; id z = @"123"; NSString *aString = [[NSString alloc] initWithFormat: @"The int %d, the C String %s, and the NSString %@", x, y, z]; - (NSUInteger)length
Returns the number of characters in the receiver.
- (NSString *)stringByAppendingString:(NSString *)aString
Returns a string object made by appending aString to the receiver. The following code snippet, for example, would produce the string “Error: unable to read file.”
NSString *errorTag = @"Error: "; NSString *errorString = @"unable to read file."; NSString *errorMessage; errorMessage = [errorTag stringByAppendingString:errorString]; - (NSComparisonResult)compare:(NSString *)otherString
Compares the receiver and otherString and returns NSOrderedAscending if the receiver is alphabetically prior to otherString, NSOrderedDescending if otherString is comes before the receiver, or NSOrderedSame if the receiver and otherString are equal.
- (NSComparisonResult)caseInsensitiveCompare:(NSString *) otherString
Like compare:, except the comparison ignores letter case.
“Inherits from” versus “Uses” or “Knows About”
Beginning Cocoa programmers are often eager to create subclasses of NSString and NSMutableArray. Don’t. Stylish Objective-C programmers almost never do. Instead, they use NSString and NSMutableArray as parts of larger objects, a technique known as composition. For example, a BankAccount class could be a subclass of NSMutableArray. After all, isn’t a bank account simply a collection of transactions? The beginner would follow this path. In contrast, the old hand would create a class BankAccount that inherited from NSObject and has an instance variable called transactions that would point to an NSMutableArray.
It is important to keep track of the difference between “uses” and “is a subclass of.” The beginner would say, “BankAccount inherits from NSMutableArray.” The old hand would say, “BankAccount uses NSMutableArray.” In the common idioms of Objective-C, “uses” is much more common than “is a subclass of.”
You will find it much easier to use a class than to subclass one. Subclassing involves more code and requires a deeper understanding of the superclass. By using composition instead of inheritance, Cocoa developers can take advantage of very powerful classes without really understanding how they work.
In a strongly typed language, such as C++, inheritance is crucial. In an untyped language, such as Objective-C, inheritance is just a hack that saves the developer some typing. There are only two inheritance diagrams in this entire book. All the other diagrams are object diagrams that indicate which objects know about which other objects. This is much more important information to a Cocoa programmer.