Using NSRange rangeOfString

user1295568 picture user1295568 · Oct 9, 2012 · Viewed 10.5k times · Source

Can someone explain what location and length represent for NSRange. If I use it in this context

NSRange range = [self.display.text rangeOfString:@"."];
if(range.location == NSNotFound){
self.display.text = [self.display.text stringByAppendingString:@"."];

What does the location represent and can someone explain this code. Also where can I find more information on properties such as location> I found it in the header file as an NSUInteger but it doesn't describe what location actually does.

Answer

tiguero picture tiguero · Oct 9, 2012

According to the official doc:

rangeofString is used to finds and returns the range of the first occurrence of a given string within the receiver.

The index of the first occurrence within your original string will be stored in the location attribute of NSRange. In case there is no occurence found the method will return NSNotFound.

So your code will append the string your are testing with '.' if this character was not found in it.