OGeek|极客世界-中国程序员成长平台

标题: ios - NSFileSystemFreeSize 返回不准确的可用磁盘空间? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:40
标题: ios - NSFileSystemFreeSize 返回不准确的可用磁盘空间?

所以我正在尝试查找我的 iPhone 上的可用磁盘空间量,并且我已经搜索了几篇较早的帖子。这些帖子中的大多数使用 NSFileManager 来检索 NSFileSystemFreeSize 值。

但是,与我在手机设置>常规>关于>可用中看到的数字相比,来自 NSFileSystemFreeSize 的数字似乎不准确。

我得到以下值:

我使用的代码:

+ (NSString*)getFreeDiskspace
{
NSDictionary *atDict = [[NSFileManager defaultManager] attributesOfFileSystemForPath"/" error:NULL];
unsigned freeSpace = [[atDict objectForKey:NSFileSystemFreeSize] unsignedIntValue];

return [NSString stringWithFormat"%u", freeSpace];
}

其他信息:

谁能向我解释为什么 NSFileSystemFreeSize 与手机和 iTunes 不匹配?任何帮助表示赞赏,谢谢!



Best Answer-推荐答案


有很多方法可以获得空闲空间

1、

NSString *tempDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSDictionary<NSFileAttributeKey, id> *att = [fileManager attributesOfFileSystemForPath:tempDir error:nil];
NSNumber *freeSize = att[NSFileSystemFreeSize];
const long long freeSpace = [freeSize longLongValue];

2、仅iOS 11或更高版本

NSURL *url = [[NSURL alloc] initFileURLWithPath:NSHomeDirectory()];
id AA = [url resourceValuesForKeys[NSURLVolumeAvailableCapacityForImportantUsageKey] error:nil][NSURLVolumeAvailableCapacityForImportantUsageKey];
NSLog(@"\nURLVolumeAvailableCapacityForImportantUsage : -----------\n%@", AA);

3、f_bavail或f_bfree供使用

- (const long long) diskSpace {
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
struct statfs tStats;
statfs([[paths lastObject] cStringUsingEncoding:NSUTF8StringEncoding], &tStats);

// for total space
//    const long long total_space = (long long)(tStats.f_blocks * tStats.f_bsize);
//    return total_space;

// for freespace:
const long long free_space = (long long)(tStats. f_bavail * tStats.f_bsize);
return free_space;

}

关于ios - NSFileSystemFreeSize 返回不准确的可用磁盘空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48467776/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4