将NSLog保存到本地文件

将NSLog保存到本地文件

本文介绍了将NSLog保存到本地文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何为iPhone进行开发,我需要将de NSLog输出保存在计算机上的本地文件中以分析结果,因为我将长时间运行该应用程序,并且需要检查一些小时运行什么输出(我想不时地将输出文件保存在我的机器上,例如每30分钟一次).

I'm learning how to develop for iPhone and i need to save de NSLog output on a local file on my machine to analyse the result in because I`ll run the application for a long time and I need to check after some hours running what was the output (and I want to save the output file on my machine from time to time, for example after every 30min).

如何将xcode输出保存到文件中?

How can I save the xcode output into a file?

推荐答案

可能不是您想要的,但是我使用了这个:

Possibly not what you want, but I use this:

- (void)logIt:(NSString *)string {
    // First send the string to NSLog
    NSLog(@"%@", string);

    // Setup date stuff
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-dd-MM"];
    NSDate *date = [NSDate date];

    // Paths - We're saving the data based on the day.
    NSString *path = [NSString stringWithFormat:@"%@-logFile.txt", [formatter stringFromDate:date]];
    NSString *writePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:path];

    // We're going to want to append new data, so get the previous data.
    NSString *fileContents = [NSString stringWithContentsOfFile:writePath encoding:NSUTF8StringEncoding error:nil];

    // Write it to the string
    string = [NSString stringWithFormat:@"%@\n%@ - %@", fileContents, [formatter stringFromDate:date], string];

    // Write to file stored at: "~/Library/Application\ Support/iPhone\ Simulator/*version*/Applications/*appGUID*/Documents/*date*-logFile.txt"
    [string writeToFile:writePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

这会将数据写入设备上的文件(每日文件).如果您希望在每次会话后将其重置,则可以肯定地修改代码来实现.

This writes the data into a file on your device (a daily file). If you want it to reset after each session you can surely modify the code to do that.

当然,您必须将所有现有的NSLog()调用更改为使用[self logIt:].

And of course you'll have to change all your existing NSLog() calls to use [self logIt:] instead.

这也可以在真实设备上使用(但是文件位置当然不同).

This also works on a real device (but the file location is different of course).

这篇关于将NSLog保存到本地文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 08:17