大约2000个字符串到一个文件

时间:2011-03-22 13:44:14

标签: iphone objective-c writetofile

我需要将单独的行放入文件中,但似乎

不支持它
    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];

它确实将一个字符串放到一个文件中,但它会覆盖以前的一个字符串。

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

要将数据附加到现有文件,请为该文件创建NSFileHandle实例,然后调用-seekToEndOfFile,最后调用-writeData:。您必须自己将字符串转换为NSData对象(使用正确的编码)。并且不要忘记在完成后关闭文件句柄。

更简单但效率更低的方法是将现有文件内容读入字符串,然后将新文本追加到该字符串并再次将所有内容写入磁盘。但是,我不会在执行2000次的循环中这样做。

答案 1 :(得分:0)

谢谢Ole!这就是我一直在寻找的。

其他人的示例代码:

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];