? ? ? 在iOS中該如何獲取磁盤總?cè)萘亢褪S嗳萘肯钢睿咳绻麤]有在項(xiàng)目中碰到這個(gè)問題,估計(jì)沒有什么人會(huì)去了解這個(gè)知識(shí)點(diǎn)怕午。正好我在項(xiàng)目中又碰到這個(gè)問題废登,就把代碼貼出來。算是拋磚引玉郁惜,希望可以幫助到有需要的人堡距。
? ? ? ?具體的應(yīng)用情景式在tableViewCell中要計(jì)算IPhone的總磁盤容量和剩余容量,使用戶可以知道是否該清楚緩存了。
? ? ? ? 在tableViewCell的label中可以直接顯示為:****M羽戒,單位為MB缤沦,當(dāng)然也可以轉(zhuǎn)化為以G為單位;代碼的話是有獲取總?cè)萘亢褪S嗳萘績刹糠帧?/p>
具體代碼如下:
1易稠、獲取手機(jī)磁盤總?cè)萘?/p>
cell.Label.text = [NSString stringWithFormat:@"%llu MB", (([self getDiskTotalSpace] / 1024) / 1024)];
具體的算法就在getDiskTotalSpace函數(shù)當(dāng)中缸废,下面我就把代碼分享給大家:
- (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;
}