tags:

views:

694

answers:

2

As an example, I want to write out some string value, str, to a file, "yy", as it changes through each iteration of a loop. Below is how I'm currently implementing it:

NSOutputStream *oStream = [[NSOutputStream alloc] initToFileAtPath:@"yy" append:NO];
[oStream open];

while ( ... )
{

    NSString *str = /* has already been set up */

    NSData *strData = [str dataUsingEncoding:NSUTF8StringEncoding];
    [oStream write:r(uint8_t *)[strData bytes] maxLength:[strData length]];

    ...
}

[oStream close];

Ignoring the UTF-8 encoding, which I do require, is this how NSStrings are typically written to a file? That is, by first converting to an NSData object, then using bytes and casting the result to uint8_t for NSOutputStream's write?

Are there alternatives that are used more often?

EDIT: Multiple NSStrings need to be appended to the same file, hence the loop above.

+1  A: 

I typically use NSString's methods writeToFile:atomically:encoding:error: or writeToURL:atomically:encoding:error: for writing to file.

See the String Programming Guide for Cocoa for more info

ctshryock
The question is not about one-shot writing, but rather incremental writing (appending) of a string to a file inside a loop.
Quinn Taylor
really? his question is "is this how NSStrings are typically written to a file". his example doesn't quite match his question.
ctshryock
+6  A: 

ctshryock's solution is a bit different than yours, since you're appending as you go, and ctshyrock's write a single file all at once (overwriting the previous version). For a long-running process, these are going to be radically different.

If you do want to write as you go, I typically use NSFileHandle here rather than NSOutputStream. It's just a little bit easier to use in my opinion.

NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:aPath];
while ( ... )
{
    NSString *str = /* has already been set up */

    [fileHandle writeData:[str dataUsingEncoding:NSUTF8StringEncoding]];
}

[fileHandle closeFile];

Note that fileHandle will automatically close when it is dealloced, but I like to go ahead and close it explicitly when I'm done with it.

Rob Napier
Is it also the case that fileHandleForWritingAtPath requires that the file already exists?
Ben Lever
No, it will create a new file in any case (removing the old one if one already exists). See the NSFileHandle docs for details on other constructors that can append to existing files.
Rob Napier
As a Cocoa beginner, I came here for information, tried this, and `fileHandleForWritingAtPath` consistently gave me `null` for nonexistent files. I had to use a POSIX `open()` with `O_CREAT` to create the file first. Does anyone have clarifying info on this, please?
Carl Smotricz