If I for example do this:
NSDirectoryEnumerator *directoryEnumerator = [[NSFileManager defaultManager] enumeratorAtURL:cacheDirectory
includingPropertiesForKeys:@[NSURLContentAccessDateKey]
options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:nil];
NSURL *fileURL;
while (fileURL = [directoryEnumerator nextObject])
{
NSDate *fileDate;
[fileURL getResourceValue:&fileDate forKey:NSURLContentAccessDateKey error:nil];
if ([cacheDate compare:fileDate] == NSOrderedDescending) // Delete all files with access date older then cacheDate(defined elsewhere)
[[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
}
Can the directory enumerator get “corrupted”, for example can I get unexpected results, because index of each file changes?
I would however like to use the enumeratorAtURL method and not contentsOfDirectoryAtURL because I have to deal with large amount of files (more then 100,000). So contentsOfDirectoryAtURL takes a lot of memory.
It’s generally a bad idea to remove items from a container while iterating through it.
You could save all
fileURLs that you want to delete in an array and then iterate through the array to delete the files.Something like this: