2013-04-10 61 views
0

我正在嘗試讀取目錄,然後獲取這些目錄中文件的路徑。問題是,我不知道有多少子目錄可能會有一個文件夾中,而這種代碼iOS閱讀多個子目錄

NSString *path; 
if ([[NSFileManager defaultManager] fileExistsAtPath:[[self downloadsDir] stringByAppendingPathComponent:[tableView cellForRowAtIndexPath:indexPath].textLabel.text]]) { 
    path = [[self downloadsDir] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", [tableView cellForRowAtIndexPath:indexPath].textLabel.text]]; 
} 
else{ 
    for (NSString *subdirs in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[self downloadsDir] error:nil]) { 
     BOOL dir; 
     [[NSFileManager defaultManager] fileExistsAtPath:[[self downloadsDir] stringByAppendingPathComponent:subdirs] isDirectory:&dir]; 
     if (dir) { 
      for (NSString *f in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[[self downloadsDir] stringByAppendingPathComponent:subdirs] error:nil]) { 
       if ([f isEqualToString:[tableView cellForRowAtIndexPath:indexPath].textLabel.text]) { 
        path = [[self downloadsDir] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@", subdirs, f]]; 
       } 
      } 
     } 
    } 
} 

只讀取了一個子目錄,並給我的文件即時尋找路徑。我找不到比這更好的方法來獲取多個子目錄以及這些目錄中文件的路徑。有人能幫忙嗎?下面有什麼即時試圖做

+Downloads Folder+ 
    +File1+ //I can get the path for this 
    +Directory1+ 
     +Directory2+ 
      +File3+ // I want to get the path for this, but don't know how 
     +File2+ // I can get the path for this 

我覺得如果我只是不斷重複的循環,獲取目錄的內容,我可能有問題也說不定。

+0

通常你會使用遞歸或隊列來做到這一點。 – Dave 2013-04-10 22:09:45

+0

@Dave我認爲遞歸會是最好的方式,但我不知道如何去做。 – 2013-04-10 22:11:02

+0

這並不難,只需將你的代碼放在一個函數中,並且每當它找到一個目錄時就使它自己調用一個新的目錄進行搜索。隊列更好,但遞歸更直觀。 – Dave 2013-04-10 22:12:31

回答

1

有一個概念叫做recursion,這個概念通常應用於像這樣的問題。 基本上,您可以爲每個子目錄調用該方法,然後每個子目錄調用 ,依此類推。

重要的是你定義了一個停止點,所以它不會永遠持續下去。似乎一個好的停止點將是一個文件或一個空目錄。

在僞代碼:

method storePaths(directory) 
    for each element in directory 
     if element is a file 
      store path 
     else if element not empty directory 
      call storePaths(element) 
+0

這是我最終做的,謝謝。 – 2013-04-10 22:24:10