我正在開發一個應用程序,我需要在不覆蓋現有數據的情況下寫入文件。我的代碼是:在iOS中的文本文件中寫入NSString而不會覆蓋數據
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];
代碼創建文件,但每次打開時,內容都會被覆蓋。一些解決方案
'seekToEndOfFile'返回的偏移量是多少?並且在測試結束時驗證文件內容? – Wain
我認爲你的代碼應該可以工作。 – trojanfoe