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
我覺得如果我只是不斷重複的循環,獲取目錄的內容,我可能有問題也說不定。
通常你會使用遞歸或隊列來做到這一點。 – Dave 2013-04-10 22:09:45
@Dave我認爲遞歸會是最好的方式,但我不知道如何去做。 – 2013-04-10 22:11:02
這並不難,只需將你的代碼放在一個函數中,並且每當它找到一個目錄時就使它自己調用一個新的目錄進行搜索。隊列更好,但遞歸更直觀。 – Dave 2013-04-10 22:12:31