Is there an easy way to check if the NSRange passed to the substring WithRange on the NSString exists (so as not to cause an error)?

Say I pass NSRange (location: 5, length: 50) to NSString "foo", this range clearly does not exist.

Is there a way to say [string rangeExists:NSRange], for example, or do we need to manually check the input?

+4
source share
1 answer

You need to write your own check, but it is quite simple:

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

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

You can create a category method in NSStringthat will add your proposed method rangeExists:. It will be simple:

- (BOOL)rangeExists:(NSRange)range {
    return range.location != NSNotFound && range.location + range.length <= self.length;
}
+13
source

Source: https://habr.com/ru/post/1619272/


All Articles