Published

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 ==

1

2

3

4

5

6

7

8

NSString*str1=@"Homebrew";

NSString*str2=@"Homebrew";

// This compares the addresses of the string

if(str1==str2)

NSLog(@"str1 equals str2");

else

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:

1

2

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:

1

2

3

4

5

6

7

8

9

10

// 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");

else

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:

1

2

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: