Changes

Jump to: navigation, search

Working with String Objects in Objective-C

1,915 bytes added, 15:30, 4 November 2009
Comparing Strings
== Comparing Strings ==
String objects cannot be compared using the equality (==) operator. The reason for this is that any attempt to perform a comparison this way will simply compare whether the two string objects are located at the same memory location. Let's take a look at this via an example:
<pre>
NSString *string1 = @"My String";
NSString *string2 = @"My String";
 
if (string1 == string2)
NSLog (@"Strings match");
else
NSLog (@"Strings do not match");
</pre>
 
In the above code excerpt, string1 and string2 are pointers to two different string objects both of which contain the same character strings. If we compare them using the equality operator, however, we will get a "Strings do not match" result. This is because the ''if (string1 == string2)'' test is asking whether the pointers point to the same memory location. Since string1 and string2 point to entirely different objects the answer, obviously, is no.
 
We can now take this a step further and change the code so that both ''string1'' and ''string2'' point to the same string object:
 
<pre>
NSString *string1 = @"My String";
NSString *string2;
 
string2 = string1;
 
if (string1 == string2)
NSLog (@"Strings match");
else
NSLog (@"Strings do not match");
</pre>
 
Now when we run the code, we get a "Strings match" result because both variables are pointing to the same object in memory.
 
To truly compare the actual strings contained within two string objects we must use the ''isEqualToString'' method:
 
<pre>
NSString *string1 = @"My String";
NSString *string2 = @"My String 2";
 
if ([string1 isEqualToString: string2])
NSLog (@"Strings match");
else
NSLog (@"Strings do not match");
</pre>
 
Another option is to use the ''compare'' (to perform a case sensitive comparison) or the ''caseInsenstiveCompare'' NSString methods. these are more advance comparison methods that can be useful when sorting strings into order.
== Checking for String Prefixes and Suffixes ==

Navigation menu