NSString methods

NSString is a class that developers use a lot. Like all Objective-C classes, it comes with useful methods. If you want to do something with a string, there is likely an NSString method that can help.

Below are a few examples of NSString methods. To introduce these methods, we are showing you the declaration of the method and then an example of it being used. The declaration tells you what you need to know about a method: whether it is an instance or a class method, what it returns, its name, and the types of its arguments, if any.

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

-​ ​(​N​S​U​I​n​t​e​g​e​r​)​l​e​n​g​t​h​;​

This method is an instance method. You can tell by the ‘-’ at the start of the declaration. (A class method would have a ‘+’ instead.) This method returns an NSUInteger and does not have any arguments. NSUInteger is a type in the Foundation framework. It is equivalent to the unsigned long type that you learned about in Chapter 7.

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

To see if one string is equal to another, you can use the isEqualToString: method:

-​ ​(​B​O​O​L​)​i​s​E​q​u​a​l​T​o​S​t​r​i​n​g​:​(​N​S​S​t​r​i​n​g​ ​*​)​o​t​h​e​r​;​

This instance method will go through the two strings comparing them character by character to see if they are the same. Its one argument is the string that you want to compare with the string that will receive the isEqualToString: message. The method returns a BOOL that reports whether the two strings are, in fact, equal.

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

To get an uppercase version of a string, you use the uppercaseString method.

-​ ​(​N​S​S​t​r​i​n​g​ ​*​)​u​p​p​e​r​c​a​s​e​S​t​r​i​n​g​;​

This instance method returns an instance of NSString that is equivalent to the receiver except all uppercase:

 ​ ​ ​ ​N​S​S​t​r​i​n​g​ ​*​a​n​g​r​y​T​e​x​t​ ​=​ ​@​"​T​h​a​t​ ​m​a​k​e​s​ ​m​e​ ​s​o​ ​m​a​d​!​"​;​
 ​ ​ ​ ​N​S​S​t​r​i​n​g​ ​*​r​e​a​l​l​y​A​n​g​r​y​T​e​x​t​ ​=​ ​[​a​n​g​r​y​T​e​x​t​ ​u​p​p​e​r​c​a​s​e​S​t​r​i​n​g​]​;​

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

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