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

Используйте NSDirectoryEnumerator, возвращаемый методом NSFileManager -enumeratorAtPath:.

+0

Можете ли вы мне посоветовать, как это сделать? –

+0

@AmiriDev Вы посмотрели [документацию для '-enumeratorAtPath:'] (https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html % 23 // apple_ref/ОКК/instm/NSFileManager/enumeratorAtPath :)? Там есть пример. – Caleb

+0

вы можете ответить на этот вопрос. http://stackoverflow.com/questions/14931224/how-to-get-the-list-of-directores-in-nsdocumentdirectory –

Смежные вопросы