有没有办法检测应用程序的已用磁盘空间?

时间:2015-03-25 12:36:40

标签: ios objective-c iphone diskspace

我需要检查我的应用程序是否使用超过300mb的磁盘空间。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

使用this answer查找文件夹的大小

- (unsigned long long int)folderSize:(NSString *)folderPath {
    NSArray *filesArray = 
     [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:folderPath 
                                                         error:nil];
    NSEnumerator *filesEnumerator = [filesArray objectEnumerator];
    NSString *fileName;
    unsigned long long int fileSize = 0;

    while (fileName = [filesEnumerator nextObject]) {
     NSDictionary *fileDictionary = 
      [[NSFileManager defaultManager] 
        attributesOfItemAtPath:[folderPath stringByAppendingPathComponent:fileName] 
                         error:nil];
        fileSize += [fileDictionary fileSize];
    }

    return fileSize;
}

请致电

NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *documentsDirectory = 
 [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                                      NSUserDomainMask, 
                                      YES) objectAtIndex:0];
NSString *cachesDirectory = 
 [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, 
                                      NSUserDomainMask, 
                                      YES) objectAtIndex:0];

unsigned long long int bundleSize = [self folderSize:bundlePath];
unsigned long long int docsSize = [self folderSize:documentsDirectory];
unsigned long long int cachesSize = [self folderSize:cachesDirectory];

long double totalSize = (bundleSize + docsSize + cachesSize)/1024.0/1024.0; 

这将为您提供应用程序的软件包,文档目录和缓存目录的大小(以兆字节为单位)。