约2000串到文件

我需要把单独的行成一个文件,但它似乎不是由支持

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; // the path to write file NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"myFile"]; [dataString writeToFile:appFile atomically:YES];

它把一个字符串到一个文件,但它会覆盖前一个。

有什么建议么?

--------------解决方案-------------

为了将数据追加到现有文件,创建一个NSFileHandle该文件的实例,然后调用-seekToEndOfFile最后-writeData: 你有你的字符串转换为NSData对象自己(用正确的编码)。 而且不要忘了,当你完成关闭文件句柄。

越容易,也不太有效的方式,是读取现有的文件内容转换为字符串,则新的文本追加到该字符串,并再次写的一切到磁盘。 我不会做,在一个循环,执行2000次,虽然。

谢谢奥莱! 这就是我一直在寻找。

换了别人一些示例代码:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

//creating a path
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"nameOfAFile"];
//clearing or creating (NSFileHande doesn't support creating a file it seems)
NSString *nothing = @""; //remember it's CLEARING! so get rid of it - if you want keep data
[nothing writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:nil];

//creating NSFileHandle and seeking for the end of file
NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:appFile];
[fh seekToEndOfFile];

//appending data do the end of file
NSString *dataString = @"All the stuff you want to add to the end of file";
NSData *data = [dataString dataUsingEncoding:NSASCIIStringEncoding];
[fh writeData:data];

//memory and leaks
[fh closeFile];
[fh release];
[dataString release];

分类:iphone 时间:2015-03-15 人气:0
分享到:

相关文章

Copyright (C) 55228885.com, All Rights Reserved.

55228885 版权所有 京ICP备15002868号

processed in 0.366 (s). 10 q(s)