Objective-C NSString + Contains

Within C# we have access to a String class from .NET which is full of helpful string manipulation methods. Many other languages have their own forms of a String library and Objective-C is right there with those languages with its NSString class. While NSString is very useful I do find it odd from time to time the naming or usage of certain methods to accomplish tasks. For example, within any .NET based language, such as C#, I have access to a handy method called String.Contains. It’ll return a true or false depending if the the string you pass as a parameter is within, or contained, within the main string object you call this method from.

The result boolean will return true in this case.

Within Objective-C’s NSString class we don’t really have a straight forward method to accomplish this task. There may be several ways of doing this but each one will require a small bit of extra work. The best solution I have found is using [NSString rangeOfString]. It’ll return an NSRange structure giving the location and length in the receiver of the first occurrence of the string. Returning {NSNotFound, 0} if the string is not found or empty. So how do you use it? Easy!

This is the easiest and simplest solution I’ve found to mimic a Contains method within Objective-C. As you can see it really isn’t too much different from return ing a simple boolean value. Just have to remember to check the location part of the returned NSRange structure. If it does not equal NSNotFound then you know the subset string is contained within your main string.

If you want more details of how to use NSString I highly recommend reading Apple’s online documentation:

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html 

Author: Scyanide

Software Engineer wanting to share his experiences.

Leave a Reply