将 NSLog 保存到本地文件中

Posted

技术标签:

【中文标题】将 NSLog 保存到本地文件中【英文标题】:Save NSLog into a Local File 【发布时间】:2014-04-04 19:51:19 【问题描述】:

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

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

【问题讨论】:

Logging to a file on the iPhone的可能重复 【参考方案1】:

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

- (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:]

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

【讨论】:

以上是关于将 NSLog 保存到本地文件中的主要内容,如果未能解决你的问题,请参考以下文章

js中如何将某地址的图片保存到本地指定文件夹中

将游戏数据本地保存到文件夹(啥文件?) - Java

使用 jquery 将表单数据保存到本地 json 文件中

jQuery或者js保存文件到本地

如何将Bitmap保存为本地图片文件?

将 CloudKit 记录保存到本地文件保存除 CKAsset 之外的所有字段