2012-01-27 73 views
-1

我已經獲取文檔目錄的路徑並在裏面創建一些目錄。我已經知道如何檢查目錄是否存在,刪除它或其文件,但是,我如何列出目錄?謝謝。iOS列表現有目錄

的文件列表,我用:

int Count; 
    NSString *path; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"SomeDirectoryName"]; 
    NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL]; 
    for (Count = 0; Count < (int)[directoryContent count]; Count++) 
    { 
     NSLog(@"File %d: %@", (Count + 1), [directoryContent objectAtIndex:Count]); 
    } 

回答

3

例如,這種方法將刪除應用程序的臨時目錄中的所有文件:

- (void)cleatTmpDirectory 
{ 
    // Create a local file manager instance 
    NSFileManager *localFileManager = [[NSFileManager alloc] init]; 
    NSURL *directoryToScan = [NSURL fileURLWithPath:[self applicationTmpDirectory]]; 

    NSDirectoryEnumerator *dirEnumerator = 
    [[localFileManager enumeratorAtURL:directoryToScan 
      includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLIsDirectoryKey,nil] 
           options: NSDirectoryEnumerationSkipsHiddenFiles    | 
     NSDirectoryEnumerationSkipsSubdirectoryDescendants | 
     NSDirectoryEnumerationSkipsPackageDescendants 
          errorHandler:nil] retain]; 

    NSError *error; 
    // Enumerate the dirEnumerator results, each value is stored in allURLs 
    for (NSURL *theURL in dirEnumerator) 
    { 
     // Retrieve whether a directory. 
     NSNumber *isDirectory; 
     [theURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL]; 

     if ([isDirectory boolValue] == NO) 
     { 
      [localFileManager removeItemAtURL:theURL error:&error]; 
     } 
    } 

    // Release the localFileManager. 
    [localFileManager release]; 
} 

你可以找到你應該使用NSDirectoryEnumerator *dirEnumerator,並傳遞給它的初始化方法適合keys,然後您將使用它。

1

使用由NSFileManager的-enumeratorAtPath:方法返回的NSDirectoryEnumerator。

+0

你能指導我該怎麼做嗎? – 2013-02-18 07:00:34

+0

@AmiriDev你看看[-enumeratorAtPath:']的文檔(https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html %23 // apple_ref/OCC/instm /的NSFileManager/enumeratorAtPath :)?這裏有一個例子。 – Caleb 2013-02-18 07:12:47

+0

你能回答這個問題嗎? http://stackoverflow.com/questions/14931224/how-to-get-the-list-of-directores-in-nsdocumentdirectory – 2013-02-18 07:21:48