2011-08-12 2 views
10

文字列をローカルリソースファイルに追加しようとしていますが、解決策を見つけるのが難しいです。私は私のアプリケーションですべての関数呼び出しのログファイルを作成しようとしているので、クラッシュした場合、どの機能が停止したかを見ることができます。iOS用のローカルリソースtxtファイルに文字列を追加する方法

log.rtfファイルを作成しましたが、このファイルに書き込めません。誰かが全体を上書きすることなくこのファイルに文字列を追加できるように助けてもらえますか?

答えて

31

私は上記の問題に対して次のコードを使用しています。

NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDir = [documentPaths objectAtIndex:0]; 
NSString *logPath = [[NSString alloc] initWithFormat:@"%@",[documentsDir stringByAppendingPathComponent:@"log.rtf"]]; 
NSFileHandle *fileHandler = [NSFileHandle fileHandleForUpdatingAtPath:logPath]; 
[fileHandler seekToEndOfFile]; 
[fileHandler writeData:[text dataUsingEncoding:NSUTF8StringEncoding]]; 
[fileHandler closeFile]; 
0
- (void)log:(NSString *)message { 
    NSMutableString *string = [[NSMutableString alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/log.txt", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]]]; 
    if (!string) string = [[NSMutableString alloc] init]; 
    [string appendFormat:@"%@\r\n", message]; 
    [string writeToFile:[NSString stringWithFormat:@"%@/log.txt", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] atomically:YES encoding:NSUTF8StringEncoding error:nil]; 
} 
+0

を行うことができます。この方法ではXCode 4.1 –

+0

から廃止されて、私は自分のコードを更新=)! – elslooo

+1

ファイルのサイズが10kを超える場合はどうなりますか?その後、可変文字列はこの大量のデータを保持することができず、アプリケーションクラッシュが発生します。これを試して私に知らせてください。 txtの文書を取る。 10kのサイズで、このコードを使って1行追加してみてください。 –

0

あなたはティム、 'WRITETOFILE:アトミック:' @この..

+ (void)WriteLogWithString:(NSString *)log 
{ 

     if(log != nil){ 

      NSString *locationFilePath = [self getLogFilePath];//access the path of file 

      FILE *fp = fopen([locationFilePath UTF8String], "a"); 

      fprintf(fp,"%s\n", [log UTF8String]); 

      fclose(fp); 
     } 

} 
+0

Sachinに感謝しますが、ファイルの終わりではなく、ファイルの開始に追加されます。 –

関連する問題