2

有没有人有例程将 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;
}
4

3 回答 3

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];
}
于 2012-04-10T21:34:26.497 回答
0

直接相当于 Swift 中的 Jody Hagins 回答:

static func prettyBytes(_ numBytes: UInt64) -> String {
    let scale: UInt64 = 1_024
    let abbrevs = [ "EB", "PB", "TB", "GB", "MB", "KB", "Bytes" ]
    var maximum = UInt64(powl(Double(scale), Double(abbrevs.count - 1)))
    for abbrev in abbrevs {
        if numBytes > maximum {
            return String(format: "%.4f %@", Double(numBytes) / Double(maximum), abbrev)
        }
        maximum /= scale
    }
    return String(format: "%u Bytes", numBytes)
}
于 2018-08-24T10:50:10.373 回答
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)
    }
}
于 2018-08-24T11:07:38.923 回答