在iOS中的文本文件中写入NSString而不覆盖数据

时间:2014-04-29 09:43:55

标签: ios objective-c

我正在开发一个应用程序,我需要写入一个文件而不会覆盖现有数据。我的代码是:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

//creating a path
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"file"];

//creating NSFileHandle and seeking for the end of file
NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:appFile];
[fh seekToEndOfFile];

//appending data do the end of file
NSString *dataString = @"Some Data";
NSData *data = [dataString dataUsingEncoding:NSASCIIStringEncoding];
[fh writeData:data];

代码创建文件,但每次打开时,内容都会被覆盖。一些解决方案?

1 个答案:

答案 0 :(得分:-3)

如果文件很大,这不是最佳解决方案。

您必须将文件的内容读入字符串。使用新数据附加字符串。并将字符串写回文件。像这样:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

//creating a path
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"file"];

 //Retriving contents of the file
NSStringEncoding enco;
NSMutableString *logStr = [NSMutableString stringWithContentsOfFile:appFile usedEncoding:&enco error:nil];

NSString *dataString = @"Some Data";
[logStr appendString:@"\n"];
[logStr appendString:dataString];
[logStr writeToFile:appFile atomically:NO encoding:NSUTF8StringEncoding error:nil];