2012-05-02 20 views
1

NSStringをファイルに書き込もうとしています。しかし、私は新しい文字列を新しい行に追加したい。対象ファイルcで上書きせずにテキストファイルを保存する方法

どうすればいいですか?

+0

あなたは問題の文字列を追加、または新しい行にそれを追加していますか? – sisve

+0

私はファイルを定期的に書き込み/更新したいので、以前のデータと新しいデータも必要です – user968597

+0

はい、現在の問題は何ですか?あなたが書き込むたびに既存のファイルを上書きするので、古いデータが消えてしまいますか? – sisve

答えて

1

あなたは、ファイルの内容を読んでその内容に新しいデータを追加して使用するファイルに新しいデータを保存することができます

// Here you set your appending text.  
NSString *yourAppendingText = @"yourAppendingText"; 

// Here you get access to the file in Documents directory of your application bundle. 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentDir = [paths objectAtIndex:0]; 
NSString *documentFile = [documentDir stringByAppendingPathComponent:@"yourFile.txt"]; 

// Here you read current existing text from that file 
NSString *textFromFile = [NSString stringWithContentsOfFile:documentFile encoding:NSUTF8StringEncoding error:nil]; 
// Here you append new text to the existing one 
NSString *textToFile = [textFromFile stringByAppendingString:yourAppendingText]; 
// Here you save the updated text to that file 
[textToFile writeToFile:documentFile atomically:YES encoding:NSUTF8StringEncoding error:nil]; 
関連する問題