Objective-C:在设备上创建文本文件并轻松检索文件

Nic*_*ard 7 iphone objective-c nslog nsstring ios

我想将自己的日志写入我的iPhone上的文本文件.我写了一个快速方法,将字符串写入文件.现在它将它保存到Documents目录中,如果在设备上下载很麻烦,因为我不能只浏览它.在我写完文件后,有没有更好的方法快速将此文件从设备中删除?

/**
 * Logs a string to file
 *
 * @version $Revision: 0.1
 */
+ (void)logWithString:(NSString *)string {

    // Create the file
    NSError *error;

    // Directory
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"log.txt"];

    // Get the file contents
    NSData *localData = [NSData dataWithContentsOfFile:filePath];
    if (localData) {
        NSString *logString = [[NSString alloc] initWithData:localData encoding:NSUTF8StringEncoding];
        string = [logString stringByAppendingFormat:@"%@\n", string];
        [logString release];
    }

    // Write to the file
    [string writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

}//end
Run Code Online (Sandbox Code Playgroud)

Luk*_*man 10

Application supports iTunes file sharing在Xcode中添加到应用程序目标的构建信息:

在此输入图像描述

然后,您可以在iTunes下方轻松浏览,检索和删除应用程序创建的任何文件Devices > Your device > Apps > File Sharing:

在此输入图像描述