2

Given a NSRange and a NSAttributedString, what's the best way to verify that the range is valid, and won't exceed the bounds of the attributed string?

I am trying to do this:

[mutableAttributedString enumerateAttribute:NSFontAttributeName inRange:underlineRange  options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id  value, NSRange range, BOOL * _Nonnull stop) {
....

However the underlineRange could be manipulated in a way that it falls outside the mutableAttributedString ranges. In that case, it ends up causing an exception.

What's the best way to handle this case? I can't find any NSAttributedString method that lets you verify that a range is valid for a given attributed string.

Z S
  • 7,039
  • 12
  • 53
  • 105
  • 1
    You need to compare `underlineRange` with `NSRange fullRange = NSMakeRange(0, mutableAttributedString.length)`. You can for instance use `NSUnionRange()` and check if the union is equal to `fullRange`. – Larme Nov 08 '18 at 18:14

1 Answers1

2
NSRange underlineRange = ...;

NSRange fullRange = NSMakeRange(0, mutableAttributedString.length);
underlineRange = NSIntersectionRange(underlineRange, fullRange);
if (underlineRange.length == 0) {
    // intersection is empty - underlineRange was entirely outside the string
} else {
    // underlineRange is now a valid range in mutableAttributedString
}
rob mayoff
  • 375,296
  • 67
  • 796
  • 848