冲坡 發表於 2024-1-9 10:29:00

MacOs - Objective-C 获取iPhone硬盘总容量及空闲容量的3种方法

<div>
<div>
<h5>方法1</h5>
<p>总容量:</p>
<div class="_2Uzcx_"><button class="VJbwyy" type="button" aria-label="复制代码"></button>
<pre class="line-numbers language-cpp highlighter-hljs" data-dark-theme="true"><code>    struct statfs buf;
    long long totalspace;
    totalspace = 0;
    if(statfs("/private/var", &amp;buf) &gt;= 0){
      totalspace = (long long)buf.f_bsize * buf.f_blocks;
    }
    return totalspace;</code></pre>
</div>
<p>空闲容量:</p>
<div class="_2Uzcx_"><button class="VJbwyy" type="button" aria-label="复制代码"></button>
<pre class="line-numbers language-cpp highlighter-hljs" data-dark-theme="true"><code>    struct statfs buf;
    long long freespace;
    freespace = 0;
    if(statfs("/private/var", &amp;buf) &gt;= 0){
      freespace = (long long)buf.f_bsize * buf.f_bfree;
    }
    return freespace;</code></pre>
</div>
<p>PS. 需要引入头文件<code>#import &lt;sys/mount.h&gt;</code></p>
<h5>方法2</h5>
<p>总容量及空闲容量:</p>
<div class="_2Uzcx_"><button class="VJbwyy" type="button" aria-label="复制代码"></button>
<pre class="line-numbers language-objectivec highlighter-hljs" data-dark-theme="true"><code>    NSDictionary *systemAttributes = [ fileSystemAttributesAtPath:NSHomeDirectory()];
    NSString *diskTotalSize = ;
    NSLog(@"磁盘大小:%@ B", diskTotalSize);
    NSLog(@"磁盘大小:%.2f GB", /1024/1024/1024);
    NSString *diskFreeSize = ;
    NSLog(@"可用空间:%@ B", diskFreeSize);
    NSLog(@"可用空间:%.2f MB", /1024/1024);</code></pre>
</div>
<p>PS. 这里所用的方法fileSystemAttributesAtPath:在 iOS 2.0 时已被宣告弃用,但在如今最新的SDK中该方法仍然可用。目前只是提示警告信息,在后续版本的 iOS SDK 中也有被移除的可能。</p>
<h5>方法3</h5>
<p>依据方法2提供的思路,加以完善。<br>总容量及空闲容量:</p>
<div class="_2Uzcx_"><button class="VJbwyy" type="button" aria-label="复制代码"></button>
<pre class="line-numbers language-objectivec highlighter-hljs" data-dark-theme="true"><code>    float totalSpace;
    float freeSpace;

    NSError *error = nil;
   
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
   
    NSDictionary *dictionary = [ attributesOfFileSystemForPath: error: &amp;error];
   
    if (dictionary) {
      
      NSNumber *fileSystemSizeInBytes = ;
      
      totalSpace = /1024.0f/1024.0f/1024.0f;
      
      NSNumber *freeFileSystemSizeInBytes = ;
      
      freeSpace = /1024.0f/1024.0f;
      
    } else {
      
      totalSpace = 0;
      
      freeSpace = 0;

    }</code></pre>
</div>
</div>
<br><br>作者:WonderChang<br>链接:https://www.jianshu.com/p/a89d8c299d31<br>来源:简书<br>著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。</div><br><br>
来源:https://www.cnblogs.com/zhuchunlin/p/17953848
頁: [1]
查看完整版本: MacOs - Objective-C 获取iPhone硬盘总容量及空闲容量的3种方法