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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM