覆盖 NSDocumentDirectory 中的前一个文件 [英] Overwriting the previous file in NSDocumentDirectory
本文介绍了覆盖 NSDocumentDirectory 中的前一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已使用此代码将字符串写入同一个文件 10 次.但它会为每次新发布覆盖以前的数据.我想将新数据附加到旧数据.
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;
}
推荐答案
使用下面的代码写入文件
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];
这篇关于覆盖 NSDocumentDirectory 中的前一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文