OS X v10.11 中弃用了 NSTextView 的 insertText 方法。什么是替代品?

NSTextView's insertText method is deprecated in OS X v10.11. What is the replacement?

我在 AppKit API 参考中看到 insertText 方法在 OS X v10.11 中被弃用。我应该用什么来代替?

文档说

- (void)insertText:(id)aString

This method is the means by which text typed by the user enters an NSTextView. See the NSInputManager class and NSTextInput protocol specifications for more information. ...

NSTextInput中有一个注释:

IMPORTANT

NSTextInput protocol is slated for deprecation. Please use NSTextInputClient protocol, introduced in OS X v10.5, as described in NSTextInputClient Protocol Reference.

NSTextInputClient协议中有一个方法

- (void)insertText:(id)aString
  replacementRange:(NSRange)replacementRange

这似乎是合适的替代品

旧方法

- (void)insertText:(id)aString

新方法

- (void)insertText:(id)aString replacementRange:(NSRange)replacementRange

在实践中使用新的 insertText 方法

// Start String: abcdef

// Result: a++bcdef
[NSTextView insertText:@"++" replacementRange:NSMakeRange(1, 0)];

// Result: a++def
[NSTextView insertText:@"++" replacementRange:NSMakeRange(1, 2)];

// Result: a++f
[NSTextView insertText:@"++" replacementRange:NSMakeRange(1, 4)];

顺便说一句,如果您要将文本粘贴到 NSTextView,请更改为使用此:

pasteAsPlainText:

苹果文档是这样写的

讨论 此方法的行为类似于 insertText: