Overwriting the previous file in NSDocumentDirectory

旧街凉风 提交于 2019-12-11 06:16:57

问题


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


来源:https://stackoverflow.com/questions/15898026/overwriting-the-previous-file-in-nsdocumentdirectory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!