i

作者: 我在鄱阳湖边 | 来源:发表于2016-11-14 17:29 被阅读357次

          在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;

    }

    相关文章

      网友评论

          本文标题: i

          本文链接:https://www.haomeiwen.com/subject/gzghpttx.html