Unable to insert text into a NSTextView programmatically


I try to append a string to the existing content of a text view.

And everything goes to pieces, so:

What am I doing wrong? Just before setting the string, a log shows that it is correct.



the class of the content of a text view is actually MSMutableAttributedString, so try this

NSAttributedString *attributedString;
attributedString = [[NSAttributedString alloc] initWithString:finalInsert]];
[[mainTextView textStorage] appendAttributedString:attributedString];
[attributedString release];

Hi Stefan,

This time I get this:


There must be another problem with glyphs.
The code in my post is the standard method to append a string to the contents of a text view

Have you previously invoked beginEditing without endEditing?

Hello Shane,

No, neither beginEditing nor endEditing.

I really don’t understand. When I log the previous text + the inserted string, everything looks fine. When I try to set the new text, I get this error.

The attributed string is bound to a attribute (property) of a Core Data entity. When I edit it in the text view, I can copy/paste, type, insert images and so on: no problem to edit, save and retrieve. Is it something wrong that the console doesn’t reveal? How could I find it?

I suspect the fact it’s not working has something to do with the way Core Data works. Can you use insertText: instead?

This time I get:

If I set the selection to the very beginning of the text with
[mainTextView setSelectedRange: NSMakeRange(0,0)];
I get:


Well, once again, the solution that I found isn’t simple, but it works and even avoid the modification of the original (i.e. the Entity Attribute), which was another goal (I formerly discarded the changes before re-opening the file :confused: ):

  1. Programmatically unbind the property from the text view;
  2. Make a copy of the entity’s attributed string in a local variable;
  3. Intall this copy as text;
  4. Append the desired strings to the text.

So the text is re-initialized at each modification. Looking back, it was not SO complicated.

Thanks to both of you!

By the way, do you know how to insert a string into a text using the current text’s font? the equivalent of the Pages’s “Paste and Apply Style”. my insertion uses the default font (Helvetica 12, which is ugly enough).

EDIT: Found. InsertText does the job. IF the textView is editable. I like the docs. It’s like searching Easter eggs :wink: