用NSFileManager实现文件夹占内存计算

NSFileManager计算文件/文件夹占内存大小

在一些软件中,一般都会给用户展现当前APP的内存,同时用户可以根据自己的需要来清除缓存的内容。一般而言,文件夹是没有大小这个属性的,所以需要遍历文件夹的内容来计算文件夹的大小,下面用NSFileManger来实现这个功能。

了解到文件/文件夹路径是一个NSString字符串类型,所以可以给字符串添加分类,如果其是文件/文件夹实现计算其大小的功能。分类命名为fileSize.

- (NSInteger)fileSize{
      //文件管理者
      NSFileManager *mgr = [NSFileManager defaultManager];
      //判断字符串是否为文件/文件夹
      BOOL dir = NO;
      BOOL exists = [mgr fileExistsAtPath:self isDirctory:&dir];
      //文件/文件夹不存在
      if (exists == NO) return 0;
      //self是文件夹
     if (dir){
          //遍历文件夹中的所有内容
          NSArray *subpaths = [mgr subpathsAtPath:self];
          //计算文件夹大小
          NSInteger totalByteSize = 0;
          for (NSString *subpath in subpaths){
             //拼接全路径                 
             NSString *fullSubPath = [self stringByAppendingPathComponent:subpath];
             //判断是否为文件
             BOOL dir = NO;
             [mgr fileExistsAtPath:fullSubPath isDirectory:&dir];
             if (dir == NO){//是文件
                    NSDictionary *attr = [mgr attributesOffItemAtPath:fullSubPath error:ni];
                    totalByteSize += [attr[NSFileSize] integerValue];
              }
          }
          return totalByteSize;      
     } else{//是文件
           NSDictionary *attr = [mgr attributesOffItemAtPath:self error:ni];
            return [attr[NSFileSize] integerValue];
   }   
}    

这样就可以实现文件/文件夹大小的计算

比如计算Caches文件的大小

NSString *caches =[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
Integer cachesSize = [caches fileSize];

如果是非文件/文件夹的字符串,大小则为0

posted @ 2016-03-10 15:43  zsper  阅读(126)  评论(0编辑  收藏  举报