Logging in a text file iPhone

柔情痞子 提交于 2019-12-25 04:19:56

问题


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.


回答1:


[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.



来源:https://stackoverflow.com/questions/3653012/logging-in-a-text-file-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!