【问题标题】:How to get storage capacity of mac programmatically?如何以编程方式获取mac的存储容量?
【发布时间】:2015-08-25 05:02:33
【问题描述】:

如何获取 Cocoa 中的总容量、可用空间和可用空间?

如屏幕截图所示,我想在我的 macOS 的 Cocoa 应用程序中以编程方式获取它。

【问题讨论】:

标签: objective-c macos cocoa storage


【解决方案1】:

使用-[NSFileManager mountedVolumeURLsIncludingResourceValuesForKeys:options:] 获取卷的NSURLs。对于propertyKeys,使用@[ NSURLVolumeTotalCapacityKey, NSURLVolumeAvailableCapacityKey ]。您可能想在选项中使用NSVolumeEnumerationSkipHiddenVolumes

然后,对于每个 URL,使用相同的属性键调用 -[NSURL resourceValuesForKeys:error:]。这将为您提供一个字典,其键是 NSURLVolumeTotalCapacityKeyNSURLVolumeAvailableCapacityKey,其值是 NSNumber 对象,包含相应的数量,以字节为单位。

如果您需要格式化这些值以进行显示,请使用NSByteCountFormatter

【讨论】:

  • 感谢您的回复。您能否通过代码向我展示获得 mac 的总容量,因为我对 mac 开发有点陌生。谢谢...
  • 这是我使用 NSURL 和 NSByteCountFormatter 的部分解决方案:NSDictionary *resources = [url resourceValuesForKeys: keys error: &error]; NSLog(@"NSURL resources: %@", resources); if ([url getResourceValue: &availableSpace forKey: NSURLVolumeAvailableCapacityKey error: &error] == YES) { NSString *formattedAvailableSpace = [NSByteCountFormatter stringFromByteCount: [availableSpace longLongValue] countStyle: NSByteCountFormatterCountStyleFile]; NSLog(@"availableSpace: %@ formattedAvailableSpace: %@", availableSpace, formattedAvailableSpace); }
【解决方案2】:

我的答案来自link

所以我发布了我使用该参考所做的事情。

    NSError *error;

    NSFileManager *fm = [NSFileManager defaultManager];
    NSDictionary *attr = [fm attributesOfFileSystemForPath:@"/"
                                                     error:&error];
    NSLog(@"Attr: %@", attr);
    float totalsizeGb = [[attr objectForKey:NSFileSystemSize]floatValue] / 1000000000;
    NSLog(@" size in GB %.2f",totalsizeGb);

    float freesizeGb = [[attr objectForKey:NSFileSystemFreeSize]floatValue] / 1000000000;
    NSLog(@" size in GB %.2f",freesizeGb);

希望对其他人也有帮助。

谢谢...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-18
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    相关资源
    最近更新 更多