Objective-C 獲取iPhone硬盤總?cè)萘考翱臻e容量的3種方法

方法1

總?cè)萘浚?/p>

    struct statfs buf;
    long long totalspace;
    totalspace = 0;
    if(statfs("/private/var", &buf) >= 0){
        totalspace = (long long)buf.f_bsize * buf.f_blocks;
    }
    return totalspace;

空閑容量:

    struct statfs buf;
    long long freespace;
    freespace = 0;
    if(statfs("/private/var", &buf) >= 0){
        freespace = (long long)buf.f_bsize * buf.f_bfree;
    }
    return freespace;

PS. 需要引入頭文件#import <sys/mount.h>

方法2

總?cè)萘考翱臻e容量:

    NSDictionary *systemAttributes = [[NSFileManager defaultManager] fileSystemAttributesAtPath:NSHomeDirectory()];
    NSString *diskTotalSize = [systemAttributes objectForKey:@"NSFileSystemSize"];
    NSLog(@"磁盤大?。?@ B", diskTotalSize);
    NSLog(@"磁盤大小:%.2f GB", [diskTotalSize floatValue]/1024/1024/1024);
    NSString *diskFreeSize = [systemAttributes objectForKey:@"NSFileSystemFreeSize"];
    NSLog(@"可用空間:%@ B", diskFreeSize);
    NSLog(@"可用空間:%.2f MB", [diskFreeSize floatValue]/1024/1024);

PS. 這里所用的方法fileSystemAttributesAtPath:在 iOS 2.0 時(shí)已被宣告棄用,但在如今最新的SDK中該方法仍然可用。目前只是提示警告信息,在后續(xù)版本的 iOS SDK 中也有被移除的可能。

方法3

依據(jù)方法2提供的思路,加以完善。
總?cè)萘考翱臻e容量:

    float totalSpace;
    float freeSpace;

    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];
        
        totalSpace = [fileSystemSizeInBytes floatValue]/1024.0f/1024.0f/1024.0f;
        
        NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];
        
        freeSpace = [freeFileSystemSizeInBytes floatValue]/1024.0f/1024.0f;
        
    } else {
        
        totalSpace = 0;
        
        freeSpace = 0;

    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • WebSocket-Swift Starscream的使用 WebSocket 是 HTML5 一種新的協(xié)議。它實(shí)...
    香橙柚子閱讀 24,779評(píng)論 8 183
  • -- 再讀傲慢與偏見(強(qiáng)烈推薦1995年英劇版《傲慢與偏見》) 偉大的愛情都會(huì)有一個(gè)情景設(shè)定:就是故事中的男女主角...
    Liina閱讀 334評(píng)論 0 1
  • 夏夜。風(fēng)兒從門縫里調(diào)皮的溜進(jìn)來,撩起我的發(fā)梢,親親我的臉龐,掠過我的胳膊……在這夏夜,你來了剛剛好。我知道你愛我,...
    慧心如蓮閱讀 1,833評(píng)論 0 1

友情鏈接更多精彩內(nèi)容