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?
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 range A contains range B, the intersection of A & B should be B, the union of A & B should be A. So in theory, both
NSEqualRanges(NSUnionRange(A, B), A)
and
NSIntersectionRange(A, B), B)
can be used to check if range A contains range B.
But if we pass a negative value to B.location, for the members of struct NSRange is NSUInteger, it will turn to a very large value. In this case,
NSUnionRange(A, B)
also returns A. It seems to be a bug. (Tested on macOS 10.14, Xcode 10.1)
so we choose NSIntersectionRange, like this:
NSString *str = @"foo";
NSRange textRange = NSMakeRange(0, str.length);
NSRange range = NSMakeRange(0, 1);
if (NSEqualRanges(NSIntersectionRange(textRange, range), range)) {
//safe
}
You can do this :
if(selectedNSRange.location != NSNotFound && NSMaxRange(selectedNSRange) <= self.text.length)