2013-04-09 81 views
1

我已經使用此代碼將字符串寫入同一個文件10次。但它覆蓋了每次新推出的以前的數據。我想將新數據追加到舊數據中。覆蓋NSDocumentDirectory中的前一個文件

[@"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; 
} 

回答

2

使用下面的代碼文件寫

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

// Create a FileHandle 
NSFileHandle *myHandle; 

放在循環多個附加操作下面的代碼

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