How do I know when an attachment attribute is being added to my NSTextView?
Asked Answered
B

3

9

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.

Berti answered 23/10, 2009 at 15:59 Comment(0)
I
5

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.

Impracticable answered 23/10, 2009 at 16:17 Comment(2)
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.Berti
As far as I can tell, -textStorageWillProcessEditing: permits more changes to the text than -textStorageDidProcessEditing:. You may want to use that instead.Beast
R
2

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.

Raspings answered 23/10, 2009 at 16:21 Comment(1)
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.Berti
T
0

Delegate methods have various corner cases. It's better to subclass NSTextStorage class.

Tanto answered 29/5, 2020 at 4:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.