2011-05-09 145 views
1

我有一个/ Documents/Images文件夹,在该文件夹中有几个以年名命名的其他文件夹,在这些文件夹中我有图像。我想删除图像文件夹中的所有内容(包括文件夹和这些文件夹中的图像)。从某个文件夹中删除所有文件和文件夹

我试了几个代码片段,但没有删除这些文件夹

我的方法:

- (void) clearCache:(NSString *) folderName{ 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectoryPath = [paths objectAtIndex:0]; 
NSFileManager *fm = [NSFileManager defaultManager]; 
NSString *directory = [documentsDirectoryPath stringByAppendingPathComponent:folderName]; 
NSLog(@"Removing items at path: %@",directory); 
    NSError *error = nil; 
BOOL succes = [fm removeItemAtPath:directory error:&error]; 

/*for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) { 
    //BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:@"%@%@", directory, file] error:&error]; 
    BOOL success = [fm removeItemAtPath:[directory stringByAppendingPathComponent:file] error:&error]; 
    if (!success || error) { 
     // it failed. 
    } 
}*/ 

}

+0

可能重复[如何在应用程序指定的目录中删除所有档案?(http://stackoverflow.com/questions/2226600/how-to-delete-all-files-in -a-specified-directory-on-the-app) – Leena 2014-08-31 10:53:42

回答

8
NSFileManager *fm = [NSFileManager defaultManager]; 
NSString *directory = [[self documentsDirectory] stringByAppendingPathComponent:@"urDirectory/"]; 
NSError *error = nil; 
for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) { 
    BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:@"%@%@", directory, file] error:&error]; 
    if (!success || error) { 
     // it failed. 
    } 
} 

希望这有助于

+1

你打算把'documentsDirectory'设置为'NSDocumentDirectory'吗? – 2014-05-06 02:49:49

相关问题