NSFileSystemFreeSize:将结果转换为用户友好的mb / gb显示?

时间:2012-04-10 15:37:09

标签: ios ios5

是否有人有例程将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;
}

3 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分:0)

与Swift中Jody Hagins答案的直接等效:

myViewHolder.textView.setVisibility(View.VISIBLE);

答案 2 :(得分:0)

Swift中对Jody Hagins的改进回答是当值为1时区分“字节”和“字节”。

static func prettyBytes(_ numBytes: UInt64) -> String {
    let scale: UInt64 = 1_024
    let abbrevs = [ "EB", "PB", "TB", "GB", "MB", "KB", "" ]
    var maximum = UInt64(powl(Double(scale), Double(abbrevs.count - 1)))
    var i = 0
    while maximum > 1, numBytes <= maximum {
        maximum /= scale
        i += 1
    }
    if maximum > 1 {
        return String(format: "%.4f %@", Double(numBytes) / Double(maximum), abbrevs[i])
    } else if numBytes != 1 {
        return String(format: "%u Bytes", numBytes)
    } else {
        return String(format: "%u Byte", numBytes)
    }
}