Objective-C provides a quick and easy way to compare 2 NSString’s and determine if they are equal. This comparison is a very strict comparison however and also verifies matching cases within strings. Often times, it is necessary to compare 2 strings and return true when the strings are the same but the cases are not. For example:

The code above would print The Strings Do Not Match to the console because when Objective-C does the comparison the cases for the strings are different.

So how then would we do a case insensitive compare? There are a few options out there for example:

The above code is a great approach but with this method  the strings will match even if one of the strings you are comparing to is nil. We could check first to ensure we do not have a nil string but there is an even easier way to ensure that we have matching case insensitive strings. See below:

In the above code notice that we are converting both strings into upper case strings. This way when we compare the strings to their uppercase counterparts, we can ignore the case all together since they will both be upper case strings.

I wrote an NSString Category based on the above code. You can download the files below:

To use the category all you have to do is include the .m and .h files in your project and then import the .h file and simply use the following code:

If you have any questions or suggestions feel free to leave a comment

Be Sociable, Share!
The following two tabs change content below.
I've been in the Geek category for as long as I can remember. I am into anything technology and Sci-Fi related. I like tinkering with electronics as well as writing applications for Mac & iPhone.

Leave a Reply

Post Navigation