首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >记录到iPhone上的文件

记录到iPhone上的文件
EN

Stack Overflow用户
提问于 2008-10-14 18:36:16
回答 5查看 29.3K关注 0票数 18

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

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

谢谢!

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2008-10-14 18:52:06

我已经成功地使用了freopen(...)将输出重定向到我自己的文件。

票数 18
EN

Stack Overflow用户

发布于 2008-10-15 02:43:25

如果你想使用Cocoa,NSString和NSData提供了读/写文件的方法,而NSFileManager提供了文件操作。下面是一个例子(应该适用于iPhone):

代码语言:javascript
运行
复制
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];
票数 32
EN

Stack Overflow用户

发布于 2010-01-21 00:38:35

这段代码很适合我..

代码语言:javascript
运行
复制
#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的组织者中查看的控制台仍然工作得很好。

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/202299

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档