Re: Storing NSString with attributes
Re: Storing NSString with attributes
- Subject: Re: Storing NSString with attributes
- From: Ali Ozer <email@hidden>
- Date: Mon, 3 Dec 2001 09:56:13 -0800
On Sunday, December 2, 2001, at 11:58 PM, Ivan Myrvold wrote:
On sxndag, desember 2, 2001, at 09:38 , Brendan Younger wrote:
On Sunday, December 2, 2001, at 11:50 AM, Ivan Myrvold wrote:
My application have two NSTextView which a user can edit texts, and
an NSOutlineView in a drawer where the user can click on a line, and
the contents of the two NSTextView's will change accordingly.
This works very well with basic text, I am using the "string" and
"setString" methods to get and set the text in the two views.
But I thought I would add the possibility to set some text
attributes, like bold and italic etc.
It was very easy to add the font menu in IB to the application, and
the thing worked also...until I changed to a new line in the outline
view.
That is probably because I use the "string" method to extract the
text from the NSTextView, and even if I have selected some text to be
bold, the string method is stripped of any such attributes.
So which method should I use to extract the text from my views? I
have read the NSText, NSAttributedString, NSTextStorage documents
without quite understanding how to do this.
NSTextStorage inherits from NSMutableAttributedString. Therefore you
can simply call -textStorage and get an NSMutableAttributed string to
do whatever you want with.
OK, so whenever I want to store away the attributed text from
myTextView , I simply do a:
NSMutableAttributedString *myAttributedString;
myAttributedString = [[myTextView textStorage] copy];
But what should I do when I want the myAttributedString back into
myTextView?
[[textView textStorage] setAttributedString: myAttributedString]
should do it. As Brendan said, NSTextStorage inherits from
NSMutableAttributedString, which inherits from NSAttributedString. The
API for these two classes are in two places:
<Foundation/NSAttributedString.h> is the basic attributed string
functionality (immutable and mutable). These define attributed string
infrastructure without defining any attributes (as concepts like font,
color, RTF are not known at the Foundation level).
<AppKit/NSAttributedString.h> adds new methods to these two classes to
do these higher level things --- define attribute names for fonts,
colors, etc; read/write documents, etc.
BTW, another way to make attributed strings persistent is to save them
off as RTF or RTFD (the latter if you have graphics or attachments in
your text). This is good for saving your attributed strings in files,
databases, etc. This will not save away your custom attributes though.
Ali