So personally I really hate NSNotFound
but understand its necessity.
But some people may not understand the complexities of comparing against NSNotFound
For example, this code:
- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
if([string rangeOfString:otherString].location != NSNotFound)
return YES;
else
return NO;
}
has its problems:
1) Obviously if otherString = nil
this code will crash. a simple test would be:
NSLog(@"does string contain string - %@", [self doesString:@"hey" containString:nil] ? @"YES": @"NO");
results in !! CRASH !!
2) What is not so obvious to someone new to objective-c is that the same code will NOT crash when string = nil
.
For example, this code:
NSLog(@"does string contain string - %@", [self doesString:nil containString:@"hey"] ? @"YES": @"NO");
and this code:
NSLog(@"does string contain string - %@", [self doesString:nil containString:nil] ? @"YES": @"NO");
will both result in
does string contains string - YES
Which is clearly NOT what you want.
So the better solution that I believe works is to use the fact that rangeOfString returns the length of 0 so then a better more reliable code is this:
- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
if(otherString && [string rangeOfString:otherString].length)
return YES;
else
return NO;
}
OR SIMPLY:
- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
return (otherString && [string rangeOfString:otherString].length);
}
which will for cases 1 and 2 will return
does string contains string - NO
That's my 2 cents ;-)
Please check out my Gist for more helpful code.
if ([string rangeOfString:@"hello"] == 0) {...}
there's a type mismatch error for NSRange and int. to fix that, you should change the line to the following:if ([string rangeOfString:@"hello"].length == 0) {...}