覆盖NSDocumentDirectory中的上一个文件

时间:2013-04-09 09:17:04

标签: objective-c xcode nsfilemanager

我已使用此代码将字符串写入同一文件10次。但它会覆盖每次新发布的先前数据。我想将新数据附加到旧数据中。

[@"one" writeToFile:[self returnDocumentsDirectory] atomically:NO encoding:NSASCIIStringEncoding error:nil];


-(NSString *)returnDocumentsDirectory
{
    NSArray *DocumentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [DocumentsDirectoryPath objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:@"History.txt"];
    return filePath;
}

1 个答案:

答案 0 :(得分:2)

使用以下代码写入文件

NSArray *DocumentsDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [DocumentsDirectoryPath objectAtIndex:0];
NSString *filePath = [path stringByAppendingPathComponent:@"History.txt"];

// Create a FileHandle
NSFileHandle *myHandle;

将以下代码放在循环中以进行多个追加操作

// Check File Exist at Location or not, if not then create new
if(![[NSFileManager defaultManager] fileExistsAtPath:filePath])
   [[NSFileManager defaultManager] createFileAtPath:filePath contents:[@"Your First String" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];

// Create handle for file to update content
myHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];

// move to the end of the file to add data
[myHandle seekToEndOfFile];

// Write data to file
[myHandle writeData:  [@"YOUr Second String" dataUsingEncoding:NSUTF8StringEncoding]];

// Close file
[myHandle closeFile];