rss feed Twitter Page Facebook Page Github Page Stack Over Flow Page

iPhone String (NSString) comparisons in objective-c

Use isEqualToString for string comparisons

While working on my last project, I encountered few problems regarding "strings". On the simulator, everything worked well, but once on the device, my app had a different behavior. I was using the basic double equals comparison:

if (MyObject.name != value1) {
   // The rest of my code ...
}

After spending few times on that issue, I realize I was comparing a NSString-typed property to a NSString variable. Therefore, I was supposed to use the "isEqualToString" comparison method instead of the double equal comparison:

if ([MyObject.name isEqualToString:value]) {
   // The rest of my code ...
}

In the iPhone Simulator (running on 10.6.2) this comparison returned false, but on the iPhone running 3.1.2 it returned true.

Never assume your result will be the same from simulator and the device.

The Compare Method

NSString object have a method called "compare". That method gives you the ability to get the difference between the two (2) strings:

Here's an example:

NSString *str = @"ubuntu";
NSComparisonResult result = [str compare:@"apple"];

switch (result) {
	case NSOrderedAscending:
		// Ascending code
		break;
	case NSOrderedSame:
		// Same code
		break;
	case NSOrderedDescending:
		// Descending code
		break;
	default:
		break;
}

You can also use the "caseInsensitiveCompare" if you like to compare these strings using case with case sensitivity.