Objective-C 获取iPhone硬盘总容量及空闲容量的3种方法

方法1

总容量:

    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

总容量及空闲容量:

    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 时已被宣告弃用,但在如今最新的SDK中该方法仍然可用。目前只是提示警告信息,在后续版本的 iOS SDK 中也有被移除的可能。

方法3

依据方法2提供的思路,加以完善。
总容量及空闲容量:

    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;

    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • WebSocket-Swift Starscream的使用 WebSocket 是 HTML5 一种新的协议。它实...
    香橙柚子阅读 24,966评论 8 183
  • -- 再读傲慢与偏见(强烈推荐1995年英剧版《傲慢与偏见》) 伟大的爱情都会有一个情景设定:就是故事中的男女主角...
    Liina阅读 360评论 0 1
  • 夏夜。风儿从门缝里调皮的溜进来,撩起我的发梢,亲亲我的脸庞,掠过我的胳膊……在这夏夜,你来了刚刚好。我知道你爱我,...
    慧心如莲阅读 1,872评论 0 1

友情链接更多精彩内容