簡體   English   中英

使用NSFileHandle創建文件后清空文檔目錄

[英]Empty documents directory after creating file with NSFileHandle

我正在為Apple Watch編寫應用程序。 我正在使用以下方法(從SE答復 )來寫入日志文件:

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

我想知道它是否寫正確,但是當我查看容器時(遵循這些SE回答 ),documents目錄為空。 在此處輸入圖片說明

我的問題是:我的文件去了哪里? 我怎么找到它?

我認為可能給您帶來問題的是NSFileHandle對象。 我已經將成千上萬的文件寫入documents文件夾,並且從未使用過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 :(");
}

根據其他研究,答案似乎是:

如果要在Apple Watch上存儲文件,該文件將存儲在其自己的容器中,該文件無法通過xcode看到。

實際上,它似乎與以下錯誤報告有關: https : //openradar.appspot.com/radar?id=5021353337946112(通過此SE查找): 如何使用Xcode6.2導出iOS應用程序的共享容器?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM