How to remove the contents in Cache directory?

ios, ios5, objective-c

Solution

NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *cacheFolderPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSError *error = nil;
NSString *dir = [cacheFolderPath stringByAppendingPathComponent:@"yourCSSSUBFolderName"];
[[NSFileManager defaultManager] removeItemAtPath:dir error:nil];

You can do the same for any other directories you want to delete!

Later if you want to add those files than first create that subfolder and than add your files for e-g:

NSArray *paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
NSString *directory = [paths objectAtIndex:0];
NSString *dirPath=[directory stringByAppendingPathComponent:@"yourCSSSUBFolderName"];
NSFileManager *fileManger=[NSFileManager defaultManager];
if(![fileManger fileExistsAtPath:dirPath])
{
    NSError *error = nil;
    [fileManger createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error];
}
// now add the directories
NSString *filePath = [dirPath stringByAppendingPathComponent:@"Yourfile.extension"];
[yourData writeToFile:filePath atomically:YES]; //Write to file

Problem

In my cache directory I have a folder named Example. That Example folder has subfolders `CSS`, `JS`. I want to remove the `CSS` subfolder. If I use this code, the entire Example folder is removed: ``` NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *cacheFolderPath = [NSSearchPathForDirectoriesInDomains(NSCacheDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSError *error = nil; for (NSString *fileName in [fileManager contentsOfDirectoryAtPath:cacheFolderPath error:&error]) { [fileManager removeItemAtPath:[cacheFolderPath stringByAppendingPathComponent:fileName] error:&error]; } ```

Original source