iOS获取磁盘容量

      在iOS中该如何获取磁盘总容量和剩余容量?如果没有在项目中碰到这个问题,估计没有什么人会去了解这个知识点。正好我在项目中又碰到这个问题,就把代码贴出来。算是抛砖引玉,希望可以帮助到有需要的人。

       具体的应用情景式在tableViewCell中要计算IPhone的总磁盘容量和剩余容量,使用户可以知道是否该清楚缓存了。

        在tableViewCell的label中可以直接显示为:****M,单位为MB,当然也可以转化为以G为单位;代码的话是有获取总容量和剩余容量两部分。


具体代码如下:

1、获取手机磁盘总容量

cell.Label.text = [NSString stringWithFormat:@"%llu MB", (([self getDiskTotalSpace] / 1024) / 1024)];

具体的算法就在getDiskTotalSpace函数当中,下面我就把代码分享给大家:

- (uint64_t)getDiskTotalSpace

{

uint64_t totalSpace = 0;

__autoreleasing 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 unsignedLongLongValue];

NSLog(@"Memory Capacity of %llu MiB.", ((totalSpace/1024ll)/1024ll));

}

else {

NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %d", [error domain], [error code]);

}

return totalSpace;

}

2、获取磁盘剩余容量

- (uint64_t)getDiskFreeSpace

{

uint64_t totalFreeSpace = 0;

__autoreleasing NSError *error = nil;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error: &error];

if (dictionary) {

NSNumber *freeFileSystemSizeInBytes = [dictionary objectForKey:NSFileSystemFreeSize];

totalFreeSpace = [freeFileSystemSizeInBytes unsignedLongLongValue];

NSLog(@"Memory Capacity of %llu.", ((totalFreeSpace/1024ll)/1024ll));

}

else {

NSLog(@"Error Obtaining System Memory Info: Domain = %@, Code = %d", [error domain], [error code]);

}

return totalFreeSpace;

}

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

相关阅读更多精彩内容

  • error code(错误代码)=0是操作成功完成。error code(错误代码)=1是功能错误。error c...
    Heikki_阅读 3,538评论 1 9
  • 1.NSLog(@"%@",[[UIDevice currentDevice] systemVersion]);/...
    Y像梦一样自由阅读 10,847评论 3 12
  • 过去的你,有做过什么到至今仍后悔的选择吗?因为什么而后悔呢?另一种选择背后的可能性?如果现在能再选一遍,你还会像当...
    寺音阅读 563评论 2 1
  • 本人觉得自己挺友善的,对身边的人都很友好~但是,真是挺喜欢独来独往的。但并不是说我是那种自闭的,和身边同学也玩得很...
    育儿有堂阅读 180评论 0 0
  • 身材看起来再完美的人,也有自己的小执念,比如希望腰再细点,脖子再长点…每个人在意的部位各不相同,没有人对自己的身材...
    Dora香识女人阅读 834评论 0 0

友情链接更多精彩内容