Question

How should I convert the contents of an NSTextView to NSData, and then convert it back and display it, on Mac OS X?

I can convert the text without formatting by using textView.textStorage.string (where textView is the NSTextView object). However, I want to save the text formatting as well.

In fact I have implemented an approach that works, but I'm not sure it is guaranteed to always work. I encode the NSTextStorage object itself and write it, and then read it back as an NSAttributedString. (NSTextStorage is a subclass of NSAttributedString.) I do this because I cannot directly set textStorage for the NSTextView, but I can set its attributed string.

Here is my code to convert it (the result is in data):

NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];          
[archiver encodeObject:textView.textStorage forKey:@"attrs"];
[archiver finishEncoding];

To read it back:

NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSAttributedString* theAttrString = [unarchiver decodeObjectForKey:@"attrs"];
[unarchiver finishDecoding];

and to display it:

[textView.textStorage setAttributedString:theAttrString];

Is this approach guaranteed to work, given that I encode an NSTextStorage object and read it back interpreting it as an NSAttributedString?

Was it helpful?

Solution

Yes, this will work. NSTextStorage will use the NSCoding implementation of NSAttributedString, so when you encode the data, you'll actually be encoding an NSAttributedString. This means that you will read the data back as an immutable object, even though you wrote a mutable object.

Obviously, that's fine if you use the setAttributedString: method, so you'll use the encoded immutable data to update the mutable state. This should work flawlessly, as long as your serialization/deserialization code is correct.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top