删除iOS中的空文件夹?

问题描述:

我在应用程序的“文档”文件夹中有大量空的临时文件夹。删除iOS中的空文件夹?

如何将它们全部删除?

我想:

NSArray *folders = [[NSFileManager defaultManager]contentsOfDirectoryAtURL:[self applicationDocumentsDirectory] includingPropertiesForKeys:[NSArray arrayWithObject:@"NSURLIsDirectoryKey"] options:0 error:nil]; 
if (folders) { 
    for (NSURL *url in folders) { 
     [[NSFileManager defaultManager]removeItemAtURL:url error:nil]; 
    } 
} 

,但它会删除所有,不仅文件夹

的这段代码只删除directiories

NSFileManager *fileManager = [[NSFileManager alloc] init]; 
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 

NSArray *files = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil]; 
for (NSString *file in files) { 
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:file]; 
    NSError *error; 
    if ([[fileManager contentsOfDirectoryAtPath:fullPath error:&error] count]==0) { 
     // check if number of files == 0 ==> empty directory 
     if (!error) { 
      // check if error set (fullPath is not a directory and we should leave it alone) 
      [fileManager removeItemAtPath:fullPath error:nil]; 
     } 
    } 
} 

如果你只是想删除所有目录(包括不为空)的片段可以简化为这样:

NSFileManager *fileManager = [[NSFileManager alloc] init]; 
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 

NSArray *files = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil]; 
for (NSString *file in files) { 
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:file]; 
    if ([fileManager contentsOfDirectoryAtPath:fullPath error:nil]) 
     [fileManager removeItemAtPath:fullPath error:nil]; 
}