-
-
Save wokalski/3130403 to your computer and use it in GitHub Desktop.
bool NSRangeContainsRange (NSRange range1, NSRange range2) { | |
BOOL retval = NO; | |
if (range1.location <= range2.location && range1.location+range1.length >= range2.length+range2.location) { | |
retval = YES;; | |
} | |
return retval; | |
} |
Actually, if you simply want to know if a range contains another one, you have to do
NSIntersectionRange(range1, range2).length > 0
@thirtified's will not work, since a range might container another one regardless of the length of the second one and NSIntersectionRange returns a range with a length of 0 if false (if range1 doesn't intersects with range2).
Ok, I see: my previously posted line fails in the case that the second range has length zero and it's location is not within the first range, thanks for pointing that out.
To fix this one would have to add another check (assuming that a range with length zero can actually be considered "contained" in another range):
NSIntersectionRange(range1, range2).length == range2.length || NSLocationInRange(range2.location, range1);
which is not really simpler than the original solution.
So, I conclude with a different attempt which in my opinion is slightly more readable than the original one:
NSLocationInRange(range2.location, range1) && NSLocationInRange(NSMaxRange(range2), range1);
Note that both solutions will return false whenever range1.length == 0
, because a range with size zero cannot contain any other range (not even a location). The original implementation will return true for this case if range1 == range2
.
Btw, there is also