1

I am creating my first Mac app, a text editor. It is document-based, and the Document.xib has an nstextview. I have made the Document class the delegate of the textview. I am implementing the method:

-(void)textViewDidChangeSelection:(NSNotification *)notification
{
NSRange range=self.textView.selectedRange;
NSLog(@" %@ ",[[self.textView textStorage] attributesAtIndex: range.location
                                              effectiveRange: &range]); 

I will be using the method call that is inside NSLog to get the attributes of selected text and update from that notification method the Underline button(pressed or not). The problem is that when the app runs and I press a key an exception is raised: an uncaught exception was raised

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

I tried debugging by a @try: @catch: block and it seems that the method as above always throws that exception. If I replace:

range.location

with

(range.location-1)

it throws that exception only when the cursor is at index 0.

Does anyone know what is happening?

4

2 回答 2

0

effectiveRange不是该方法用来确定扫描属性范围的范围。返回时,该范围将包含属性和值与索引attributeAtIndex 相同的范围(即,该方法将为您的范围变量分配不同的值)。

如果要限制该方法用于查找选定范围的属性的范围,请使用以下方法并将 rangeLimit 设置为选定范围:

(NSDictionary *)attributesAtIndex:(NSUInteger)index 最长有效范围:(NSRangePointer)aRange inRange:(NSRange)rangeLimit

-(void)textViewDidChangeSelection:(NSNotification *)notification
{
    NSRange selectedRange=self.textView.selectedRange;
    NSRange effectiveRange;
    if(selectedRange.length > 0) {
        NSLog(@" %@ ",[[self.textView textStorage] attributesAtIndex:selectedRange.location
       longestEffectiveRange:&effectiveRange inRange:selectedRange]); 
    }
}

当 selectedRange 长度为 0 时,该方法似乎不起作用。这就是为什么在调用 selectedRange.length 之前检查它的原因。

于 2013-07-31T11:45:46.330 回答
0

这个线程已经有一段时间了,但无论如何我发现了这个,它是否对任何人都有用:

调用 - attributesAtIndex: 当 range.length == 0 时仍然可以正常工作,但是当位置位于字符串末尾时它会失败。这显然是一个错误,因为范围 {string_length, 0} 是一个有效范围。

为了克服这个问题,我使用 -typingAttributes: 来提供当前打字风格的属性。

NSRange currange = [self.textViewEditor selectedRange];
NSLog(@"range %@", NSStringFromRange(currange));
NSDictionary *dict;
if (currange.length==0)
    dict = [self.textViewEditor typingAttributes];
else
    dict = [self.textViewEditor.textStorage attributesAtIndex:currange.location effectiveRange:&range];
于 2014-01-23T20:57:26.353 回答