views:

249

answers:

2

Because of the semantics of certain NSTextView attachments in my application, I want to know when they are inserted or deleted from my text storage.

My subclass of NSTextView implements the shouldChangeTextInRange:replacementString: method, which allows me to easily see when an attachment is about to be replaced (I can search the text storage at the specified range).

Because the replacement string is just an NSString and not an NSAttributedString, I have no way of seeing from this method whether an attachment is being inserted. The documentation even goes so far as to say that the string may be nil if "only attributes" are being edited.

So the question is, what's the best override point to see when an attachment is being inserted? Or perhaps as useful: what's the best override point to see when attributes are being modified?

Update: I said above I had no way of knowing whether an attachment is being inserted. It's pointed out to me that I can tell that "an" attachment is involved, because the string will contain the magic NSAttachmentCharacter. But I won't have specific information about the attachment until after the edit is complete.

+3  A: 

I would take a look at the NSTextStorage delegate method -textStorageDidProcessEditing:, which should be called each time a change is made to the underlying text storage. You can then use the -editedRange, -editedMask, and -changeInLength methods to determine what section of the text storage was changed, and look in that range for any attachments that might be of interest to you.

Brian Webster
Thanks, Brian. It's not as ideal as I hoped for but it does seem like it will do the trick. It's a shame that they don't include the attributes in the shouldChange… method.
danielpunkass
+1  A: 

You might want to take a look at two NSTextStorage delegate methods:

  • (void)textStorageWillProcessEditing:(NSNotification )notification; / Delegate can change the characters or attributes */
  • (void)textStorageDidProcessEditing:(NSNotification )notification; / Delegate can change the attributes */

Inside textStorageWill/DidProcessEditing, you can call -[NSTextStorage editedMask] and -[NSTextStorage editedRange] to find out what changed and then take action accordingly.

Jonathan Hammer
Hi Jonathan - thanks for commenting. I voted your answer up but decided to accept Brian's because it was moments earlier and because it had accumulated a couple extra votes.
danielpunkass