NSString is another class like NSDate. Instances of NSString hold character strings. In code, you can create a literal instance of NSString like this;
NSString *lament = @"Why me!?";
In your TimeAfterTime project, you typed in this code:
NSLog(@"The date is %@", now);
NSLog() is an Objective-C function (not a method!) that works a lot like printf(). In NSLog(), however, the format string is actually an instance of NSString.
Instances of NSString can also be created programmatically using the stringWithFormat: class method:
NSString *x = [NSString stringWithFormat:@"The best number is %d", 5];
To get the number of characters in a string, you use the length method:
NSUInteger charCount = [x length];
And you check to see if two strings are equal using the isEqual: method:
if ([lament isEqual:x]) NSLog(@"%@ and %@ are equal", lament, x);
The C language also has a character string construct. Here’s what the preceding string examples would look like in C:
char *lament = "Why me!?"; char *x; asprintf(&x, "The best number is %d", 5); size_t charCount = strlen(x); if (strcmp(lament, x) == 0) printf("%s and %s are equaln", lament, x); free(x);
We will discuss C strings in Chapter 34. But whenever you have a choice, use NSString objects instead of C strings. The NSString class has many methods designed to make your life easier. Plus, NSString (which is based on the UNICODE standard) is exceedingly good at holding text from any language on the planet. Strange characters? No problem. Text that reads from right to left? No worries.
There is a class called NSHost which has information about your computer. To get an instance of NSHost, you can use the NSHost class method currentHost. This method returns a pointer to an NSHost object:
+ (NSHost *)currentHost
To get the localized name of your computer, you can use the NSHost instance method localizedName that returns a pointer to an NSString object:
- (NSString *)localizedName
Write a Foundation Command Line Tool that prints out the name of your computer. (This sometimes takes a surprisingly long time to run.)