iPhoneアプリケーションのファイルまたはデータベースにログステートメントを書き込むための最良の方法は何でしょうか?
理想的には、NSLog()出力はfreopen()を使用してファイルにリダイレクトできますが、それが機能しないという報告をいくつか見ました。誰かがこれをすでに行っているか、これをどのように行うのが最善かについて何か考えがありますか?
ありがとう!
Cocoa を使用する場合、NSString と NSData にはファイルの読み取り/書き込みのためのメソッドがあり、NSFileManager はファイル操作を提供します。例を次に示します (iPhone で動作するはずです)。
NSData *dataToWrite = [[NSString stringWithString:@"String to write"] dataUsingEncoding:NSUTF8StringEncoding];
NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [docsDirectory stringByAppendingPathComponent:@"fileName.txt"];
// Write the file
[dataToWrite writeToFile:path atomically:YES];
// Read the file
NSString *stringFromFile = [[NSString alloc] initWithContentsOfFile:path];
// Check if file exists
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager fileExistsAtPath:path]; // Returns a BOOL
// Remove the file
[fileManager removeItemAtPath:path error:NULL];
// Cleanup
[stringFromFile release];
[fileManager release];
電話で freopen(...) を使用して、出力を自分のファイルにリダイレクトすることに成功しました。
このコードは私にとってうまく機能します..
#if TARGET_IPHONE_SIMULATOR == 0
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *logPath = [documentsDirectory stringByAppendingPathComponent:@"console.log"];
freopen([logPath cStringUsingEncoding:NSASCIIStringEncoding],"a+",stderr);
#endif
次に、ここで概説されている方法を使用して、iPhone からログ ファイルを取得できますhttp://blog.coriolis.ch/2009/01/09/redirect-nslog-to-a-file-on-the-iphone/#more- 85
freopen を使用すると、XCODE のコンソールが機能しなくなることに注意してください。ただし、何らかの理由で、xcode のオーガナイザーで表示できるコンソールは引き続き正常に機能します。
このコードは私のために働きます:
- (void)applicationDidFinishLaunching:(UIApplication *)application {
#if TARGET_IPHONE_SIMULATOR == 0
freopen([@"/tmp/my_logs.txt" fileSystemRepresentation], "w", stderr);
#endif
}
Cocoa Lumberjackの使用を検討してください。これは、NSLog 機能を置き換える軽量で柔軟なユーティリティです。私の意見では、これは Log4J と同じクラスにあり、カスタム アペンダーなどを使用できます。たとえば、SQLiteロガーがあります。