質問
iPhoneアプリケーションでログステートメントをファイルまたはデータベースに書き込む最良の方法は何ですか?
NS誰もがすでにこれを行っているか、これをどのように行うのが最善かというアイデアを持っていますか?ありがとう!
解決
電話機で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];
このコードは私に最適です。
#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
この後、 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
}
ココア木こりの使用を検討してください。 NSLogの機能を置き換えるための軽量で柔軟なユーティリティです。私の意見では、それはLog4Jと同じクラスにあり、カスタムアペンダーなどを可能にします。たとえば、SQLiteロガーがあります。
所属していません StackOverflow