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

发布时间 2024-01-09 10:32:54作者: [BORUTO]
方法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;

    }


作者:WonderChang
链接:https://www.jianshu.com/p/a89d8c299d31
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。