2012-01-27 63 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