14
NSString

NSString is another class like NSDate. Instances of NSString hold character strings. In code, you can create a literal instance of NSString like this;

 ​ ​ ​ ​N​S​S​t​r​i​n​g​ ​*​l​a​m​e​n​t​ ​=​ ​@​"​W​h​y​ ​m​e​!​?​"​;​

In your TimeAfterTime project, you typed in this code:

 ​ ​ ​ ​ ​ ​ ​ ​N​S​L​o​g​(​@​"​T​h​e​ ​d​a​t​e​ ​i​s​ ​%​@​"​,​ ​n​o​w​)​;​

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:

 ​ ​ ​ ​N​S​S​t​r​i​n​g​ ​*​x​ ​=​ ​[​N​S​S​t​r​i​n​g​ ​s​t​r​i​n​g​W​i​t​h​F​o​r​m​a​t​:​@​"​T​h​e​ ​b​e​s​t​ ​n​u​m​b​e​r​ ​i​s​ ​%​d​"​,​ ​5​]​;​

To get the number of characters in a string, you use the length method:

 ​ ​ ​ ​N​S​U​I​n​t​e​g​e​r​ ​c​h​a​r​C​o​u​n​t​ ​=​ ​[​x​ ​l​e​n​g​t​h​]​;​

And you check to see if two strings are equal using the isEqual: method:

 ​ ​ ​ ​i​f​ ​(​[​l​a​m​e​n​t​ ​i​s​E​q​u​a​l​:​x​]​)​
 ​ ​ ​ ​ ​ ​ ​ ​N​S​L​o​g​(​@​"​%​@​ ​a​n​d​ ​%​@​ ​a​r​e​ ​e​q​u​a​l​"​,​ ​l​a​m​e​n​t​,​ ​x​)​;​

The C language also has a character string construct. Here’s what the preceding string examples would look like in C:

 ​ ​ ​ ​c​h​a​r​ ​*​l​a​m​e​n​t​ ​=​ ​"​W​h​y​ ​m​e​!​?​"​;​
 ​ ​ ​ ​c​h​a​r​ ​*​x​;​
 ​ ​ ​ ​a​s​p​r​i​n​t​f​(​&​x​,​ ​"​T​h​e​ ​b​e​s​t​ ​n​u​m​b​e​r​ ​i​s​ ​%​d​"​,​ ​5​)​;​
 ​ ​ ​ ​s​i​z​e​_​t​ ​c​h​a​r​C​o​u​n​t​ ​=​ ​s​t​r​l​e​n​(​x​)​;​
 ​ ​ ​ ​i​f​ ​(​s​t​r​c​m​p​(​l​a​m​e​n​t​,​ ​x​)​ ​=​=​ ​0​)​
 ​ ​ ​ ​ ​ ​ ​ ​p​r​i​n​t​f​(​"​%​s​ ​a​n​d​ ​%​s​ ​a​r​e​ ​e​q​u​a​l​​n​"​,​ ​l​a​m​e​n​t​,​ ​x​)​;​
 ​ ​ ​ ​f​r​e​e​(​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.

Challenge

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:

+​ ​(​N​S​H​o​s​t​ ​*​)​c​u​r​r​e​n​t​H​o​s​t​

To get the localized name of your computer, you can use the NSHost instance method localizedName that returns a pointer to an NSString object:

-​ ​(​N​S​S​t​r​i​n​g​ ​*​)​l​o​c​a​l​i​z​e​d​N​a​m​e​

Write a Foundation Command Line Tool that prints out the name of your computer. (This sometimes takes a surprisingly long time to run.)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset