将日志语句写入iPhone应用程序中的文件或数据库的最佳方法是什么?
理想情况下,可以使用freopen()将NSLog()输出重定向到一个文件,但是我看到一些报告说它不起作用。有没有人已经这样做了,或者有任何想法可以最好地做到这一点?
谢谢!
发布于 2008-10-14 18:52:06
我已经成功地使用了freopen(...)将输出重定向到我自己的文件。
发布于 2008-10-15 02:43:25
如果你想使用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];发布于 2010-01-21 00:38:35
这段代码很适合我..
#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方法从iphone上获取日志文件。
请注意,使用freopen将使XCODE中的控制台停止工作。然而,由于某些原因,你可以在xcode的组织者中查看的控制台仍然工作得很好。
https://stackoverflow.com/questions/202299
复制相似问题