iOS Development

Course No. 10-152-139

Chapter 16 — NSString

NSString *lament = @"Why me!?";

The NSString class

  • The NSString class is used in Objective-C whenever we want to use and create strings.
  • A pointer to an Objective-C string.
  • We can create a literal string with the @ symbol before a pair of quotation marks.

NSLog

  • NSLog is a function, not a method. You can see this because it uses a set of parentheses, “()” and not a pair of square brackets, “[]”.
  • You can use the printf format codes in NSLog.
  • You can also use the %@ format code for Objective-C strings.

Class references

Using the Documentation. Apple maintains a class reference for each class in its APIs.

  • NSString class reference.
    • In Xcode, select Help → Documentation and API Reference. In the search field at the top of the window, enter NSString.


    • Then select the first NSString entry (the one with the C for class), and you will be presented with the NSString class reference documentation.


    • You can click on the highlighted buttons to show/hide the panes on the left.


    • This is a common way developers have the window arranged.


stringWithFormat:

  • Click on Creating and Initializing Strings on the left panel. Then click on stringWithFormat: on the large right panel and read the documentation for the method.


  • We can create a new NSString with the stringWithFormat: method. It works like this.
    • Declare a pointer to an NSString object.
  • Then use the class method that creates a new string.
  • Inside the @"" you use format codes just like in printf and NSLog.

length

  • We find the length of a string by sending the length message.
    • (The NSUInteger type is an unsigned int that changes size based on the OS version we’re using. That’s handy.)

isEqualToString:

  • Why can’t we do this to see if two strings are the same?
  • Here’s why.


    • The == operator only compares the value of the pointers when you compare objects. You need to use a method to look inside the objects when comparing them.
  • What happens if you try to do this? Xcode will show you this:


  • When we want to see if one string has the same value as another we use a method.

caseInsensitiveCompare:

  • If you just happen to need to compare strings without caring about their case you might like this code sample.
    • Example: How do we tell if “Wolf” and “wolf” are the same if we ignore case? The isEqualToString: method will return false since they are not exactly the same string.
  • We use the caseInsensitiveCompare: method. It doesn’t return a simple BOOL. It can return three values depending on where the strings sort compared to each other.