I've got the following code that inserts a new NSAttributedString
into NSTextView
. This works fine on all versions of macOS 10.14+, however when the NSTextView
is empty, the following code causes an immediate crash when inserting any amount of string. I've tried all variants of trying to replace / append string, but it seems internally NSTextView uses replaceCharactersInRange
which seems to be the causes of the crash.
This is a method added to an extension / category on NSTextView
:
- (void) insertAttributedString:(nonnull NSAttributedString *)attribString {
NSTextStorage *textStorage = [self textStorage];
NSRange selectedRange = [self selectedRange];
if (selectedRange.location == NSNotFound) {
selectedRange = NSMakeRange([textStorage length], 0);
}
if ([self shouldChangeTextInRange:selectedRange replacementString:[attribString string]]) {
[textStorage beginEditing];
[textStorage replaceCharactersInRange:selectedRange withAttributedString:attribString];
[textStorage endEditing];
if ([self respondsToSelector:@selector(didChangeText)]) {
[self didChangeText];
}
}
}
The exception thrown is always the following:
Exception Type: SIGSEGV
Exception Codes: SEGV_MAPERR at 0x18
Crashed Thread: 0
Thread 0 Crashed:
0 CoreFoundation 0x00007fffaf21334a CFStorageInsertValues + 26
1 Foundation 0x00007fffb0c49559 -[NSBigMutableString replaceCharactersInRange:withString:] + 1093
2 Foundation 0x00007fffb0c2ce1b -[NSConcreteMutableAttributedString replaceCharactersInRange:withString:] + 336
3 UIFoundation 0x00007fffc1ece41c __NSConcreteTextStorageLockedForwarding + 48
4 UIFoundation 0x00007fffc1ece3e5 -[NSConcreteTextStorage replaceCharactersInRange:withString:] + 79
Any ideas on how to get around this on macOS 10.12 / 10.13? The only way I was able to prevent it from crashing was if I was to assign a newly allocated NSTextStorage
when NSTextView
is empty - however this then causes the app to crash when undoing the change. I don't think that's the correct approach.