View Full Version : NSTextView archiving and unarchiving

Feb 17, 2009, 07:25 PM
For the life of me I can't figure out how to archive and unarchive the content of an NSTextView. I want to be able to put some text into it, save it to a file, and have that text pop up when I start the app back up again. I do not want to use bindings at all, as my more specific purpose makes using them impossible.

My current attempts something like this

NSData *dataToWrite = [NSKeyedArchiver archivedDataWithRootObject: [theTextView textContainer]];
[dataToWrite writeToFile:[@"~/Documents/test.test" stringByExpandingTildeInPath] atomically:YES];

Then I put something in the awakeFromNib like this

NSTextContainer *tempText = [NSKeyedUnarchiver unarchiveObjectWithData:[NSData dataWithContentsOfFile:[@"~/Documents/test.test" stringByExpandingTildeInPath]]];
[theTextView replaceTextContainer: tempText];

So far this has not worked. It saves. You can go to the file, open it with plist editor, and verify that you have saved a NSTextContainer. I just can't load it back into the blashed textView.

Feb 17, 2009, 09:23 PM
Why are you saving the actual text view? Is there anything special that you're doing that requires this? Why not just save the raw text or RTFD data (RTFDFromRange:)?

(FYI it's probably not working because NSTextContainer doesn't hold the text, NSTextStorage does.)

Feb 18, 2009, 06:23 AM
NSTextStorage does, but there is no method for initializing with or replacing the TextStorage item so I havent figured out how to make it useful. Also NSTextContainer does store the text, if you open up the save file in text edit you can search and find whatever text you entered among the gibberish. I am not saving to RTFD because I want to save the textview along with several other pieces of data as instance variables of an object which I have several of in an array.

Feb 18, 2009, 07:33 AM
Here's how I'd do it. In each object in the array, store an NSData object that represents the RTFD data (or NSString if you don't need attributes). Then I'd make the class conform to the NSCoding protocol, and then encode the entire array and write it to file. You can set and get the RTFD data of an NSTextView by reading directly from its text storage which is just a special NSMutableAttributedString.

Feb 18, 2009, 03:55 PM
Thanks KainJow. Understanding the textStorage as a NSMutableAttributedString really helped :)