NSTextView: Get text changes (insertions and deletions)

cocoa, macos, nstextview

Solution

There are several delegate methods that should do what you are looking for:

– textView:shouldChangeTextInRange:replacementString:
– textView:shouldChangeTextInRanges:replacementStrings:
– textView:shouldChangeTypingAttributes:toAttributes:
– textViewDidChangeTypingAttributes:

Problem

I've got an `NSTextView` and I get the `-textDidChange:` notification. From that, I can get the current string value of the whole textview, but I can't figure out how to tell what's been deleted and added. For example, if the string in the text view was `This is a string` and the user deleted the `g`, how can I be made aware of that change? Is there a way to achieve this, preferably without subclassing?

Original source