2011-03-22 23 views
0

我需要把不同的行成一個文件,但它似乎不是由關於2000字符串文件

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

    // the path to write file 
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"myFile"]; 

    [dataString writeToFile:appFile atomically:YES]; 

支持它把一個字符串到一個文件,但它會覆蓋前一個。

有什麼建議嗎?

回答

2

要將數據追加到現有文件,請爲該文件創建一個NSFileHandle實例,然後調用-seekToEndOfFile,最後調用-writeData:。您必須自己將字符串轉換爲NSData對象(使用正確的編碼)。當你完成後別忘了關閉文件句柄。

更簡單但效率更低的方法是將現有文件內容讀入字符串,然後將新文本附加到該字符串並將所有內容再次寫入磁盤。不過,我不會在執行2000次的循環中這樣做。

+1

此外,他們真的應該想想做所有的寫操作在一重傳,而不是2000個人寫的。後者會慢很多,特別是在閃存上。 – 2011-03-22 17:54:18

+0

對Brad的評論+1。 – 2011-03-22 18:40:01

0

謝謝Ole!這就是我一直在尋找的。

爲其他一些示例代碼:

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

//creating a path 
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"nameOfAFile"]; 
//clearing or creating (NSFileHande doesn't support creating a file it seems) 
NSString *nothing = @""; //remember it's CLEARING! so get rid of it - if you want keep data 
[nothing writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:nil]; 

//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 = @"All the stuff you want to add to the end of file";   
NSData *data = [dataString dataUsingEncoding:NSASCIIStringEncoding]; 
[fh writeData:data]; 

//memory and leaks 
[fh closeFile]; 
[fh release]; 
[dataString release];