views:

40

answers:

1

Hi,

I have a score system and I would like to log all scores in a text file separated by line breaks. Here is my current save code:

NSData *dataToWrite = [[NSString stringWithFormat:@"String to write ID:%i \n",random] dataUsingEncoding:NSUTF8StringEncoding];

 NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
 NSString *path = [docsDirectory stringByAppendingPathComponent:@"text.txt"];

 // Write the file
 [dataToWrite writeToFile:path atomically:YES];

When retrieving this data, I only see the latest save. How do I make it so it saves all in a list?

Thanks.

+2  A: 

[dataToWrite writeToFile:path atomically:YES]; overwrites the file at that location, replacing whatever is there with the contents of dataToWrite.

You can likely use NSFileHandle's fileHandleForWritingAtPath: and then call seekToEndOfFile to append to said file.


Do you have an example?

Try something like:

NSFileHandle *f = [NSFileHandle fileHandleForWritingAtPath: p];
[f seekToEndOfFile];
[f writeData: d];
[f close];

All typed into SO; the compiler/runtime might differ with my opinions of correctness.

bbum
Do you have an example?
Alex
Works! Thank you. How would I delete the contents of the file?
Alex
`dataToWrite = @""; [dataToWrite writeToFile:path atomically:YES];`
Emil
If you're satisfied with this answer, you should accept it by clicking the ✔ next to the answer. This rewards the author of the answer.
Emil