1

我正在尝试将 NSString 写入文件。它正在成功写入,但是我想将新字符串附加到新行。

怎么能做到这一点?

4

1 回答 1

1

您可以读取文件内容,将新数据附加到该内容并将新数据保存到您使用的文件中:

// Here you set your appending text.    
NSString *yourAppendingText = @"yourAppendingText";  

// Here you get access to the file in Documents directory of your application bundle.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [paths objectAtIndex:0];
NSString *documentFile = [documentDir stringByAppendingPathComponent:@"yourFile.txt"];

// Here you read current existing text from that file
NSString *textFromFile = [NSString stringWithContentsOfFile:documentFile encoding:NSUTF8StringEncoding error:nil];
// Here you append new text to the existing one
NSString *textToFile = [textFromFile stringByAppendingString:yourAppendingText];
// Here you save the updated text to that file
[textToFile writeToFile:documentFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
于 2012-05-02T06:28:35.737 回答