Удалить пустые папки в iOS? - PullRequest
2 голосов
/ 01 апреля 2012

У меня есть много пустых временных папок в папке документа приложения.

Как удалить их все?

Я пытался:

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];
    }
}

, но он удаляет все,не только папки

1 Ответ

2 голосов
/ 12 мая 2012

Этот фрагмент кода удаляет только директории , которые пусты .

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];
}
...