Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy method to check is an NSRange passed to substringWithRange on NSString exists (so not to cause an error)?

Say I pass the NSRange of (location: 5, length: 50) on the NSString "foo", that range obviously doesn't exist.

Is there a way to say [string rangeExists:NSRange] for instance, or do we have to manually validate the input?

like image 747
Doug Smith Avatar asked Dec 09 '15 22:12

Doug Smith


1 Answers

You have to write your own check but it's simple enough:

NSString *str = ... // some string
NSRange range = ... // some range to be used on str

if (range.location != NSNotFound && range.location + range.length <= str.length) {
    // It's safe to use range on str
}

You could create a category method on NSString that adds your proposed rangeExists: method. It would just be:

- (BOOL)rangeExists:(NSRange)range {
    return range.location != NSNotFound && range.location + range.length <= self.length;
}
like image 114
rmaddy Avatar answered Sep 18 '22 12:09

rmaddy