Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

hiddenpremise

macrumors regular
Original poster
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
Code:
NSData *dataToWrite = [NSKeyedArchiver archivedDataWithRootObject: [theTextView textContainer]];
[dataToWrite writeToFile:[@"~/Documents/test.test" stringByExpandingTildeInPath] atomically:YES];
Then I put something in the awakeFromNib like this
Code:
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.
 

kainjow

Moderator emeritus
Jun 15, 2000
7,958
7
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.)
 

hiddenpremise

macrumors regular
Original poster
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.
 

kainjow

Moderator emeritus
Jun 15, 2000
7,958
7
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.