textfile question


Of all the silly things...

I have not yet figured out how to read/write a simple textfile. NS(Un)Archive is a nice way to load/save files, but if the file I want to read is already in text form then I don't see a good way to do it. The best thought I've had (I haven't tried it yet) is NSFile<->NSData<->NSString, but there must be a better way to do it.

What I would really like is an equivalent to NS(Un)Archive that reads/writes in human-readable text form, at least for those objects which can be easily expressed that way.

Any thoughts/suggestions would be appreciated.
That's basically what you do. Look at the TextEdit source, in DocumentReadWrite.m


NSData *data = [[textStorage string] dataUsingEncoding:encoding];
success = data && [data writeToFile:actualFileNameToSave atomically:YES];
NSString has a method for creating a string from the contents of a file. I don't remember if it has an inverse operation for writing.

You can use the following methods:

– (BOOL)writeToFile:(NSString *)path

– (id)initWithContentsOfFile:(NSString *)path


// Writing string to file:
NSString * someString = @"Contents of string...";
[someString writeToFile: @"file.txt" atomically: NO];

// Reading file into string:
NSString * otherString = [[NSString alloc] initWithContentsOfFile: @"file.txt"];

Good luck,

Edit: disabled smilies