3

对于我的语法高亮实现,我观察到NSTextViewusing的变化-[<NSTextStorageDelegate> textStorageDidProcessEditing:]

- (void)textStorageDidProcessEditing:(NSNotification *)notification {
  if (!self.languageGrammar) return;
  NSTextStorage *textStorage = self.textView.textStorage;
  NSRange glyphRange = [self.textView.layoutManager glyphRangeForBoundingRect:self.scrollView.documentVisibleRect
                                                              inTextContainer:self.textView.textContainer];
  NSRange editedRange = [self.textView.layoutManager characterRangeForGlyphRange:glyphRange actualGlyphRange:NULL];

  [textStorage removeAttribute:NSForegroundColorAttributeName range:editedRange];
  // crash is the line above ^^^^
  // color text ...
}

我想获得可见字符的范围。上面的代码一直有效,直到我点击backspace,这使它崩溃:

*** -[NSConcreteTextStorage attributesAtIndex:effectiveRange:]: Range or index out of bounds

如何获得可见字符的范围以便为它们着色?

4

1 回答 1

2

检查范围是否超出整个字符串的范围,以及是否将范围设置为适合字符串的范围:

NSRange range = NSRangeFromString(string);
于 2012-01-17T19:45:21.447 回答