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 ==
NSString *str1 = @"Homebrew";
NSString *str2 = @"Homebrew";
// This compares the addresses of the string
if (str1 == str2)
  NSLog (@"str1 equals str2");
  NSLog (@"str1 does not equal str2");

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:

NSLog (@"str1 address in memory: %p", str1);
NSLog (@"str2 address in memory: %p", str2);

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:

// Create a C string
char *cStr = "Homebrew";
NSString *str3 = [NSString stringWithUTF8String:cStr];
NSString *str4 = @"Homebrew";
// Wrong - this compares the address of the string
if (str3 == str4)
  NSLog (@"str3 equals str4");
  NSLog (@"str3 does not equal str4");

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:

NSLog (@"str3 address in memory: %p", str3);
NSLog (@"str4 address in memory: %p", str4);

Compare NSString Objects with isEqualToString

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

char *cStr = "Homebrew";
NSString *str3 = [NSString stringWithUTF8String:cStr];
NSString *str4 = @"Homebrew";
if ([str3 isEqualToString:str4])
  NSLog (@"str3 equals str4");
  NSLog (@"str3 does not equal str4");


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”.

by Patrick on Jan 9, 2010. #

When I used the method, I get an error:

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

by Chris on Apr 1, 2010. #

Hey Chris, compiles on my end. Make sure you don’t have a typo somewhere…

by John Muchow on Apr 1, 2010. #

@Chris your method needs a capital T in isEqualToString

by Jens on Jun 2, 2010. #

It works.Thanks.

by KALEES on Apr 10, 2011. #

THX a lot

by aa on Mar 22, 2012. #