how do i get size of folder NSCachesDirectory i.e /Library/Cache. i want to know size 开发者_C百科of this folder so that i can eventually clear this.
thanks.
Edit: here is my code.
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:folderPath error:&error];
if (attributes != nil) {
if (fileSize = [attributes objectForKey:NSFileSize]) {
NSLog(@"size of :%@ = %qi\n",folderPath, [fileSize unsignedLongLongValue]);
}
}
when i run this it gives my file size 768(dont know bytes or KB) and i check in finder it shows me folder size 168KB. i dont know whats wrong.
Something like the following should help get you started:
- (unsigned long long int) cacheFolderSize {
NSFileManager *_manager = [NSFileManager defaultManager];
NSArray *_cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *_cacheDirectory = [_cachePaths objectAtIndex:0];
NSArray *_cacheFileList;
NSEnumerator *_cacheEnumerator;
NSString *_cacheFilePath;
unsigned long long int _cacheFolderSize = 0;
_cacheFileList = [_manager subpathsAtPath:_cacheDirectory];
_cacheEnumerator = [_cacheFileList objectEnumerator];
while (_cacheFilePath = [_cacheEnumerator nextObject]) {
NSDictionary *_cacheFileAttributes = [_manager fileAttributesAtPath:[_cacheDirectory stringByAppendingPathComponent:_cacheFilePath] traverseLink:YES];
_cacheFolderSize += [_cacheFileAttributes fileSize];
}
return _cacheFolderSize;
}
EDIT
The value returned will be in bytes: cf. http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html#//apple_ref/doc/c_ref/NSFileSize
Assuming you are running this in the Simulator, Finder is probably reporting usage of file blocks for those bytes. Those blocks will necessarily be larger than the file data itself. Read up on the HFS+ system to learn about blocks: http://en.wikipedia.org/wiki/HFS_Plus
I'm not sure what file system is used on the iPhone, or what the file block size will be on the device, so while the byte total will be the same, the actual disk usage may be different between Simulator and device.
Do you really mean /Library/Cache, or do you mean ~/Library/Cache (the application's cache directory). You generally have no control over the former, so I'll assume you mean the latter.
Use NSFileManager's -enumeratorAtPath: to walk the directory and use -attributesOfItemAtPath:error: to fetch the fileSize. I recommend doing this slowly on a background thread to avoid blocking your app.
精彩评论