使用NSFileHandle创建文件后清空文档目录

时间:2017-08-23 19:14:45

标签: ios objective-c xcode watchkit

我正在为Apple手表编写应用程序。我使用以下方法(从this SE answer)写入日志文件:

- (void) writeLogWith: (NSString *) content {

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

    //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];

    return;
}

我通过插入手机并直接在手表上运行来运行它。该函数肯定正在执行(我已经考虑过调试器)并且它也知道该文件存在并且不会反复尝试创建它。

Xcode告诉我文件信息是:

Printing description of documentsDirectory:
/var/mobile/Containers/Data/PluginKitPlugin/8503AD6C-6EC9-4522-A867-27109B01B615/Documents
Printing description of documentsDirectory:
(NSString *) documentsDirectory = 0x16d66890
Printing description of fileName:
(NSString *) fileName = 0x16d66950
Printing description of fileName:
/var/mobile/Containers/Data/PluginKitPlugin/8503AD6C-6EC9-4522-A867-27109B01B615/Documents/whathappened.md

我想知道它是否正确写东西,但是当我查看容器时(these SE answers之后),文档目录为空。 enter image description here

我的问题是:我的文件去了哪里?我怎么能找到它?

2 个答案:

答案 0 :(得分:0)

我认为可能给你问题的是NSFileHandle对象。我已经将数千个文件写入文档文件夹,但我从未使用NSFileHandle来执行此操作。只需使用NSString上的内置方法将字符串写入文件路径。

试试这个:

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [[documentsDirectory stringByAppendingPathComponent:@"whathappened"] stringByAppendingPathExtension:@"md"];

if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
}

NSString *string = @"The String You Want To Write.";

NSError *error;
[string writeToFile:filePath atomically:false encoding:NSUTF8StringEncoding error:&error];

if (error) {
    NSLog(@"There was an error writing file\n%@", error.localizedDescription);
}

if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
    NSLog(@"File exists :)");
}
else {
    NSLog(@"File does not exist :(");
}

答案 1 :(得分:0)

从其他研究来看,答案似乎是:

如果您在Apple Watch上存储文件,它将存储在自己的容器中,而这个容器通过xcode无法看到。

确实,似乎与此错误报告有关:https://openradar.appspot.com/radar?id=5021353337946112,通过此SE找到:How to export shared container of an iOS App with Xcode6.2?