iOS 获取内存大小使用情况(进度条显示)

一、获取设备内存大小方法

//返回存储内存占用比例
- (NSString *)getFreeDiskspaceRate{

    float totalSpace;
    float totalFreeSpace=0.f;
    
    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];
    if (dictionary) {
        NSNumber *fileSystemSizeInBytes = [dictionary objectForKey: NSFileSystemSize];
        NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
        totalSpace = [fileSystemSizeInBytes floatValue]/1024.0f/1024.0f/1024.0f;
        totalFreeSpace = [freeFileSystemSizeInBytes floatValue]/1024.0f/1024.0f/1024.0f;

        //totalString、freeString是定义两个全局变量 进度条上显示大小数据用
        totalString = [self getFileSizeString:[fileSystemSizeInBytes floatValue]];
        freeString = [self getFileSizeString:[freeFileSystemSizeInBytes floatValue]];
        NSLog(@"打印totalString:%@,freeString:%@",totalString,freeString);
      
        NSLog(@"Memory Capacity of %.2f GB with %.2f GB Free memory available.", totalSpace, totalFreeSpace);
        
    } else {
        NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %@", [error domain], [error code]);

    }
    NSString *freeStr = [NSString stringWithFormat:@"%.3f",(totalSpace-totalFreeSpace)/totalSpace];//进度条比例
    return freeStr;
}

 

//补充:另一种获取内存大小的方法

首先导入#include <sys/param.h>和#include <sys/mount.h>

方法:

NSFileManager *fm = [NSFileManager defaultManager];
    NSDictionary *fat = [fm attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
    NSLog(@"容量:%lldG 可用容量:%lldG",[[fat objectForKey:NSFileSystemSize]longLongValue]/1000000000,[[fat objectForKey:NSFileSystemFreeSize]longLongValue]/1000000000);
    struct statfs buf;
    long long freespace = -1;
    if(statfs("/var", &buf) >= 0){
        freespace = (long long)(buf.f_bsize * buf.f_bfree);
    }
    NSLog(@"%@",[NSString stringWithFormat:@"手机剩余存储空间为:%qi GB" ,freespace/1024/1024/1024]);

 

二、转换内存大小为单位数值的方法(根据实际情况得到G、M、KB单位)

-(NSString *)getFileSizeString:(CGFloat)size
{
    if (size>1024*1024*1024){
        return [NSString stringWithFormat:@"%.1fG",size/1024/1024/1024];//大于1G,则转化成G单位的字符串
    }
    else if(size<1024*1024*1024&&size>=1024*1024)//大于1M,则转化成M单位的字符串
    {
        return [NSString stringWithFormat:@"%.1fM",size/1024/1024];
    }
    else if(size>=1024&&size<1024*1024) //不到1M,但是超过了1KB,则转化成KB单位
    {
        return [NSString stringWithFormat:@"%.1fK",size/1024];
    }
    else//剩下的都是小于1K的,则转化成B单位
    {
        return [NSString stringWithFormat:@"%.1fB",size];
    }
}

 

三、虚拟机上的效果图(这里截图显示的空间大小数值比较大,说明实际是电脑的内存情况,真机上显示就正常了)

 

四、其他

参考网址:http://www.bubuko.com/infodetail-922638.html

posted @ 2016-04-21 21:12  wusang  阅读(5436)  评论(0编辑  收藏  举报