(iPhone/iPad)计算缓存文件大小


(iPhone/iPad)计算缓存文件大小:

  1. FileSize.h  
  2. //   
  3. // FileSize.h   
  4. //    
  5. //   
  6.   
  7. #import <Cocoa/Cocoa.h>   
  8.   
  9.   
  10. @interface FileSize : NSObject {  
  11.   
  12. }  
  13. // This method converts a given # of bytes into human readable format (KB, MB, GB)   
  14. - (NSString *)stringFromFileSize:(int)theSize;  
  15. // Returns the size of a file in bytes   
  16. - (int)sizeOfFile:(NSString *)path;  
  17. // Returns the size of a folder in bytes   
  18. - (int)sizeOfFolder:(NSString *)path;  
  19. @end  
  20.   
  21. FileSize.m  
  22.   
  23. // FileSize.m   
  24. // Created by PCWiz on 30/07/09.   
  25.   
  26. #import "FileSize.h"   
  27.   
  28.   
  29. @implementation FileSize  
  30. - (NSString *)stringFromFileSize:(int)theSize  
  31. {  
  32. float floatSize = theSize;  
  33. if (theSize<1023)  
  34. return([NSString stringWithFormat:@"%i bytes",theSize]);  
  35. floatSize = floatSize / 1024;  
  36. if (floatSize<1023)  
  37. return([NSString stringWithFormat:@"%1.1f KB",floatSize]);  
  38. floatSize = floatSize / 1024;  
  39. if (floatSize<1023)  
  40. return([NSString stringWithFormat:@"%1.1f MB",floatSize]);  
  41. floatSize = floatSize / 1024;  
  42.   
  43. return([NSString stringWithFormat:@"%1.1f GB",floatSize]);  
  44. }  
  45.   
  46. - (int)sizeOfFile:(NSString *)path  
  47. {  
  48. NSDictionary *fattrib = [[NSFileManager defaultManager] fileAttributesAtPath:path traverseLink:YES];  
  49. int fileSize = (int)[fattrib fileSize];  
  50. return fileSize;  
  51. }  
  52.   
  53. - (int)sizeOfFolder:(NSString*)folderPath  
  54. {  
  55. NSArray *contents;  
  56. NSEnumerator *enumerator;  
  57. NSString *path;  
  58. contents = [[NSFileManager defaultManager] subpathsAtPath:folderPath];  
  59. enumerator = [contents objectEnumerator];  
  60. int fileSizeInt = 0;  
  61. while (path = [enumerator nextObject]) {  
  62. NSDictionary *fattrib = [[NSFileManager defaultManager] fileAttributesAtPath:[folderPath stringByAppendingPathComponent:path] traverseLink:YES];  
  63. fileSizeInt +=[fattrib fileSize];  
  64. }  
  65. return fileSizeInt;  
  66. }  
  67. @end  

相关内容