Overwriting the previous file in NSDocumentDirecto

2019-07-23 02:42发布

问题:

I have used this code to write a string to the same file 10 times . But it is overwriting the previous data for every new launch. I want to append the new data to the old data .

[@"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:

Use following code to write in file

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

// Create a FileHandle
NSFileHandle *myHandle;

Put following code in loop for multiple append operation

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