Compare NSString Objects (Updated)

This tip is for those new to Objective-C and Cocoa and walks through some basics on comparing NSString objects for equality.

Compare NSString objects with ==


Although this seems to give the results we are after (see the figure below showing Xcode console output), the reason this works is that the compiler can manage strings internally when you define them using the shortcut method (@”stringhere”) and will store only one reference internally to duplicates. You can verify that the strings refer to the same content by looking at the locations in memory where the variables are stored:

As shown in the figure below, notice the addresses are the same for both strings.

Let’s modify the above code to compare two more strings, this time with one of the strings being created from a C string:

Looking at the memory addresses we can do a quick sanity check, notice in the figure below that the addresses are not equal, even though the string “Homebrew” is the same for each variable:

Compare NSString Objects with isEqualToString

The right way to go about this is use the isEqualToString: method in the NSString class:

  1. Thanks. I’ve run into this a couple of times, even though it’s been mentioned a few times elsewhere.

    The problem (actually my problem) is that my brain sees the “str1” construction and translates it to “contents of string 1” rather than “address of string 1”.

  2. When I used the method, I get an error:

    ‘NSString’ may not respond to ‘-isEqualtoString:’

  3. @Chris your method needs a capital T in isEqualToString

Comments are closed.