Skip to content

Commit 18334bc

Browse files
committed
Add -calculateSizeWithCompletionBlock:.
This method provides a way to asynchronously calculate the size of the disk cache, reporting both the number of files and the total file size. This is useful when querying large disk caches because the file system enumeration operation can take some time.
1 parent 48ce95f commit 18334bc

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

SDWebImage/SDImageCache.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,4 +154,9 @@ typedef enum SDImageCacheType SDImageCacheType;
154154
*/
155155
- (int)getDiskCount;
156156

157+
/**
158+
* Asynchronously calculate the disk cache's size.
159+
*/
160+
- (void)calculateSizeWithCompletionBlock:(void (^)(NSUInteger fileCount, unsigned long long totalSize))completionBlock;
161+
157162
@end

SDWebImage/SDImageCache.m

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -423,4 +423,37 @@ - (int)getDiskCount
423423
return count;
424424
}
425425

426+
- (void)calculateSizeWithCompletionBlock:(void (^)(NSUInteger fileCount, unsigned long long totalSize))completionBlock
427+
{
428+
NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
429+
430+
dispatch_async(self.ioQueue, ^
431+
{
432+
NSUInteger fileCount = 0;
433+
unsigned long long totalSize = 0;
434+
435+
NSFileManager *fileManager = [NSFileManager defaultManager];
436+
NSDirectoryEnumerator *fileEnumerator = [fileManager enumeratorAtURL:diskCacheURL
437+
includingPropertiesForKeys:@[ NSFileSize ]
438+
options:NSDirectoryEnumerationSkipsHiddenFiles
439+
errorHandler:NULL];
440+
441+
for (NSURL *fileURL in fileEnumerator)
442+
{
443+
NSNumber *fileSize;
444+
[fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL];
445+
totalSize += [fileSize unsignedLongLongValue];
446+
fileCount += 1;
447+
}
448+
449+
if (completionBlock)
450+
{
451+
dispatch_async(dispatch_get_main_queue(), ^
452+
{
453+
completionBlock(fileCount, totalSize);
454+
});
455+
}
456+
});
457+
}
458+
426459
@end

0 commit comments

Comments
 (0)