2013-04-22 73 views
1

我試圖使用the solution here中看到的方法刪除我正在編寫的應用程序的iPhone文檔目錄中的所有文件。爲了傳入文檔目錄的字符串位置,我對解決方案中的代碼做了一些小的修改。我的代碼版本如下:iOS - iPhone應用程序文檔「沒有這樣的目錄」?

NSString *directory = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] absoluteString]; 
NSLog(@"%@", directory); 
NSError *error = nil; 
NSArray *directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:directory error:&error]; 
if (error == nil) { 
    for (NSString *path in directoryContents) { 
     NSString *fullPath = [directory stringByAppendingPathComponent:path]; 
     BOOL removeSuccess = [[NSFileManager defaultManager] removeItemAtPath:fullPath error:&error]; 
     if (!removeSuccess) { 
      // Error handling 
     } 
    } 
} else { 
    // Error handling 
    NSLog(@"%@", error); 
} 

當我嘗試但是運行此,directoryContents的設置,由於真實傳遞什麼被解釋爲一個不存在的目錄失敗。具體而言,這兩個的NSLog()語句,我已經把代碼返回如下:

2013-04-22 11:48:22.628 iphone-ipcamera[389:907] file://localhost/var/mobile/Applications/AB039CDA-412B-435A-90C2-8FBAADFE6B1E/Documents/ 

2013-04-22 11:48:22.650 iphone-ipcamera[389:907] Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x1d5232c0 {NSUnderlyingError=0x1d54c420 "The operation couldn’t be completed. No such file or directory", NSFilePath=file://localhost/var/mobile/Applications/AB039CDA-412B-435A-90C2-8FBAADFE6B1E/Documents/, NSUserStringVariant=(

    Folder 

)} 

至於我可以看到被打印到NSLog的路徑看起來是正確的,所以我不知道我是什麼做錯了。任何人都可以指出我的錯誤在哪裏?非常感謝!

回答

8

您的代碼得到directory的值不太對。你想:

NSURL *directoryURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; 
NSString *directory = [directoryURL path]; 

調用上NSURLabsoluteString給你一個文件的URL。您不需要文件URL,您需要將文件URL轉換爲文件路徑。這是path方法的作用。

另一種方法是:

NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
+0

勝利。謝謝你,先生。按照描述工作,我很欣賞關於爲什麼我以前的方法不起作用的解釋。 – golmschenk 2013-04-22 16:28:39

+0

更好的是,調用' - [NSFileManager contentsOfDirectoryAtURL:...]'並避免完全使用路徑 – 2013-04-24 22:13:01

+0

使用'path'而不是'absoluteString'解決了我的問題! – Fogh 2014-03-05 07:57:52

相關問題