我是 OSX Lion 下 Cocoa 编程的新手,所以这是一个我找不到答案的问题。我需要修改用户通过NSTextView
. 编辑可能包括替换字符串中的某些部分NSTextStorage
以及添加NSTextAttachment
对象。我实现了协议并将其NSTextView
作为委托提供。我还以以下方式实现了该方法textView:shouldChangeTextInRanges:replacementStrings:
:
- (BOOL)textView:(NSTextView *)textView shouldChangeTextInRanges:(NSArray *)affectedRanges replacementStrings:(NSArray *)replacementStrings{
NSTextStorage* ts=[textView textStorage];
[ts beginEditing];
NSMutableString* buf=[ts mutableString];
//make some completions
NSRange rng;
rng.location=0;
rng.length=[buf length];
[buf replaceOccurrencesOfString:@"(." withString:@"(0." options:0 range:rng];
rng.location=0;
rng.length=[buf length];
[buf replaceOccurrencesOfString:@"-+" withString:@"-" options:0 range:rng];
rng.location=0;
rng.length=[buf length];
[buf replaceOccurrencesOfString:@"+-" withString:@"-" options:0 range:rng];
[ts endEditing];
return YES;
}
因此我尝试了下一个场景:当应用程序启动时,用户在NSTextView
一些文本中键入。如果他输入“(。”一切顺利。但是当他输入“-+”(减号、加号、空格)时,该方法崩溃并产生此转储:
[NSConcreteTextStorage attributesAtIndex:effectiveRange:]: Range or index out of bounds
(
0 CoreFoundation 0x00007fff95963286 __exceptionPreprocess + 198
1 libobjc.A.dylib 0x00007fff8c32bd5e objc_exception_throw + 43
2 CoreFoundation 0x00007fff959630ba +[NSException raise:format:arguments:] + 106
3 CoreFoundation 0x00007fff95963044 +[NSException raise:format:] + 116
4 AppKit 0x00007fff90acb5bd -[NSConcreteTextStorage attributesAtIndex:effectiveRange:] + 121
5 AppKit 0x00007fff90f4cde6 -[NSTextView insertText:replacementRange:] + 840
6 AppKit 0x00007fff910fc891 -[NSTextInputContext handleTSMEvent:] + 2289
7 AppKit 0x00007fff910fe4fe _NSTSMEventHandler + 165
8 HIToolbox 0x00007fff89745308 _ZL23DispatchEventToHandlersP14EventTargetRecP14OpaqueEventRefP14HandlerCallRec + 1263
9 HIToolbox 0x00007fff89744914 _ZL30SendEventToEventTargetInternalP14OpaqueEventRefP20OpaqueEventTargetRefP14HandlerCallRec + 446
10 HIToolbox 0x00007fff8975b6c7 SendEventToEventTarget + 76
11 HIToolbox 0x00007fff89930a4d SendTSMEvent + 35
12 HIToolbox 0x00007fff89930dd4 SendUnicodeTextAEToUnicodeDoc + 452
13 HIToolbox 0x00007fff8993095e TSMKeyEvent + 629
14 HIToolbox 0x00007fff8976f81a TSMProcessRawKeyEvent + 2350
15 AppKit 0x00007fff910fbade -[NSTextInputContext handleEvent:] + 639
16 AppKit 0x00007fff90fc7eaf -[NSView interpretKeyEvents:] + 248
17 AppKit 0x00007fff90f40c65 -[NSTextView keyDown:] + 691
18 AppKit 0x00007fff90a20544 -[NSWindow sendEvent:] + 7430
19 AppKit 0x00007fff909b868f -[NSApplication sendEvent:] + 5593
20 AppKit 0x00007fff9094e682 -[NSApplication run] + 555
21 AppKit 0x00007fff90bcd80c NSApplicationMain + 867
22 myapp 0x0000000100001302 main + 34
23 myapp 0x00000001000012d4 start + 52
似乎缩短的字符串会导致一些越界溢出。
我做错了什么,我该如何解决这个问题?请帮忙。