将NSLog保存到本地文件中

时间:2014-04-04 19:51:19

标签: ios iphone objective-c xcode5 output

我正在学习如何为iPhone开发,我需要在我的机器上的本地文件中保存de NSLog输出来分析结果,因为我将运行应用程序很长一段时间我需要检查几个小时后运行什么是输出(我想不时在我的机器上保存输出文件,例如每30分钟后)。

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

1 个答案:

答案 0 :(得分:2)

可能不是你想要的,但我用这个:

- (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];
}

这会将数据写入设备上的文件(每日文件)。如果您希望在每次会话后重置它,您肯定可以修改代码来执行此操作。

当然,您必须更改所有现有的NSLog()来电,才能使用[self logIt:]

这也适用于真实设备(但文件位置当然不同)。