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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With