Skip to content

Commit

Permalink
Merge pull request #307 from nebillo/master
Browse files Browse the repository at this point in the history
Optimizing enumeration of files while cleaning the disk cache
  • Loading branch information
Olivier Poitrey committed Feb 21, 2013
2 parents ae57215 + fbf14d2 commit 05dd3f4
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions SDWebImage/SDImageCache.m
Expand Up @@ -256,14 +256,29 @@ - (void)cleanDisk
dispatch_async(self.ioQueue, ^
{
NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.maxCacheAge];
NSDirectoryEnumerator *fileEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:self.diskCachePath];
for (NSString *fileName in fileEnumerator)
// convert NSString path to NSURL path
NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
// build an enumerator by also prefetching file properties we want to read
NSDirectoryEnumerator *fileEnumerator = [[NSFileManager defaultManager] enumeratorAtURL:diskCacheURL
includingPropertiesForKeys:@[ NSURLIsDirectoryKey, NSURLContentModificationDateKey ]
options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:NULL];
for (NSURL *fileURL in fileEnumerator)
{
NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName];
NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
if ([[[attrs fileModificationDate] laterDate:expirationDate] isEqualToDate:expirationDate])
// skip folder
NSNumber *isDirectory;
[fileURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL];
if ([isDirectory boolValue])
{
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
continue;
}

// compare file date with the max age
NSDate *fileModificationDate;
[fileURL getResourceValue:&fileModificationDate forKey:NSURLContentModificationDateKey error:NULL];
if ([[fileModificationDate laterDate:expirationDate] isEqualToDate:expirationDate])
{
[[NSFileManager defaultManager] removeItemAtURL:fileURL error:nil];
}
}
});
Expand Down

0 comments on commit 05dd3f4

Please sign in to comment.