MacOs - 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;
}
作者:WonderChang
链接:https://www.jianshu.com/p/a89d8c299d31
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具