objective-cnsattributedstringnsrangensrangeexception

NSAttributedString: check if NSRange is valid


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.


Solution

  • 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
    }