18

将日志语句写入 iPhone 应用程序中的文件或数据库的最佳方式是什么?

理想情况下,可以使用 freopen() 将 NSLog() 输出重定向到文件,但我已经看到一些报告说它不起作用。有没有人已经这样做了,或者有任何想法如何最好地做到这一点?

谢谢!

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 回答