在iOS应用中创建日志文件 [英] Creating a Log File in an iOS app

查看:93
本文介绍了在iOS应用中创建日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以在我的应用程序中,我有一堆数据,我想写入日志文件,然后在单击按钮时在 UITextView 中显示它。我知道如何切换UITextView,但我不知道如何创建和更新日志文件(在本地文件系统中)。感谢您的帮助。

So in my app I have a bunch of data that I'd like to write to a log file, and then display it within a UITextView when I click a button. I know how to toggle the UITextView, but I have no idea how to create and update a log file (in the local filesystem). Thanks for any help.

推荐答案

基本思路是您创建文件,并在每次登录新文件时附加到该文件线。你可以很容易地做到这一点:

The basic idea is that you create the file, and append to it every time you log a new line. You can do it quite easily like this:

写入文件:

NSString *content = @"This is my log";

//Get the file path
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:@"myFileName.txt"];

//create file if it doesn't exist
if(![[NSFileManager defaultManager] fileExistsAtPath:fileName])
    [[NSFileManager defaultManager] createFileAtPath:fileName contents:nil attributes:nil];

//append text to file (you'll probably want to add a newline every write)
NSFileHandle *file = [NSFileHandle fileHandleForUpdatingAtPath:fileName];
[file seekToEndOfFile];
[file writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
[file closeFile];

阅读:

//get file path
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:@"myFileName.txt"];

//read the whole file as a single string
NSString *content = [NSString stringWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:nil];

这篇关于在iOS应用中创建日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆