18

iPhoneアプリケーションのファイルまたはデータベースにログステートメントを書き込むための最良の方法は何でしょうか?

理想的には、NSLog()出力はfreopen()を使用してファイルにリダイレクトできますが、それが機能しないという報告をいくつか見ました。誰かがこれをすでに行っているか、これをどのように行うのが最善かについて何か考えがありますか?

ありがとう!

4

5 に答える 5

32

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];
于 2008-10-15T02:43:25.327 に答える
18

電話で freopen(...) を使用して、出力を自分のファイルにリダイレクトすることに成功しました。

于 2008-10-14T18:52:05.873 に答える
14

このコードは私にとってうまく機能します..

#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 のオーガナイザーで表示できるコンソールは引き続き正常に機能します。

于 2010-01-20T16:38:34.700 に答える
11

このコードは私のために働きます:

- (void)applicationDidFinishLaunching:(UIApplication *)application {
#if TARGET_IPHONE_SIMULATOR == 0
    freopen([@"/tmp/my_logs.txt" fileSystemRepresentation], "w", stderr);
#endif
}
于 2009-01-26T11:56:47.757 に答える
3

Cocoa Lumberjackの使用を検討してください。これは、NSLog 機能を置き換える軽量で柔軟なユーティリティです。私の意見では、これは Log4J と同じクラスにあり、カスタム アペンダーなどを使用できます。たとえば、SQLiteロガーがあります。

于 2011-12-28T15:44:21.887 に答える