2012-04-10 122 views
1

有没有人有一个例程来将NSFileSystemFreeSize的结果转换为可用的mb/gb的用户友好字符串。我认为我有这个要点,但我得到的结果很奇怪。NSFileSystemFreeSize:将结果转换为用户友好的mb/gb显示?

- (NSString*)getFreeSpace 
{ 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 

NSDictionary* fileAttributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:documentsDirectory error:NULL]; 
unsigned long long freeSpaceInBytes = [[fileAttributes objectForKey:NSFileSystemFreeSize] unsignedLongLongValue]; 

NSString * space = [NSString stringWithFormat:@"Free Space: %fll", freeSpaceInBytes /1024./1024. /1024.]; 

NSLog(@"freeSpaceInBytes %llull %fll", freeSpaceInBytes, freeSpaceInBytes /1024./1024. /1024.); 

return space; 
} 

回答

6
static NSString* prettyBytes(uint64_t numBytes) 
{ 
    uint64_t const scale = 1024; 
    char const * abbrevs[] = { "EB", "PB", "TB", "GB", "MB", "KB", "Bytes" }; 
    size_t numAbbrevs = sizeof(abbrevs)/sizeof(abbrevs[0]); 
    uint64_t maximum = powl(scale, numAbbrevs-1); 
    for (size_t i = 0; i < numAbbrevs-1; ++i) { 
     if (numBytes > maximum) { 
      return [NSString stringWithFormat:@"%.4f %s", numBytes/(double)maximum, abbrevs[i]]; 
     } 
     maximum /= scale; 
    } 
    return [NSString stringWithFormat:@"%u Bytes", (unsigned)numBytes]; 
} 
+0

这就是甜!谢谢。我永远不会想出如此优雅的东西。 – 2012-04-10 22:01:33

+0

嘿,我是新来的Objective-C,我想知道如何登录这个NSString。的NSLog(@ “%@”,prettyBytes);不工作'Format指定类型'id',但参数的类型为'NSString *(*)(uint64_t)''。 – iDev 2014-07-25 10:04:59

+0

你正在发送它的功能本身。你需要调用它的东西......'NSLog(@“%@”,prettyBytes(someNumberOfBytes))' – 2014-07-26 02:23:49

相关问题