User1234 User1234 - 6 months ago 84
Objective-C Question

How to get file size properly and convert it to MB, GB in Cocoa?


Possible Duplicate:

ObjC/Cocoa class for converting size to human-readable string?




I'm new in Cocoa. I'm trying to get size of folder files properly. And display it in MB if it less 1 GB , or in GB.

The way I want it to display is rounded with one number after point.

Example
5.5 MB if it is more than 1000 > 1.1 GB

I'm trying to use this

unsigned long long size= ([[[NSFileManager defaultManager] attributesOfItemAtPath:fullPath error:nil] fileSize]);


But I can't a way properly convert number, and display it , as I want.

Thanks.

Answer

For converting file size to MB, Gb use below function

- (id)transformedValue:(id)value
{

    double convertedValue = [value doubleValue];
    int multiplyFactor = 0;

    NSArray *tokens = [NSArray arrayWithObjects:@"bytes",@"KB",@"MB",@"GB",@"TB",@“PB”, @“EB”, @“ZB”, @“YB”,nil];

    while (convertedValue > 1024) {
        convertedValue /= 1024;
        multiplyFactor++;
    }

    return [NSString stringWithFormat:@"%4.2f %@",convertedValue, [tokens objectAtIndex:multiplyFactor]];
}

EDIT:

You can also use NSByteCountFormatter class. Available in iOS 6.0 / OS X v10.8 and later.

[NSByteCountFormatter stringFromByteCount:1999 countStyle:NSByteCountFormatterCountStyleFile];

You can use NSByteCountFormatterCountStyleFile, NSByteCountFormatterCountStyleMemory, NSByteCountFormatterCountStyleDecimal or NSByteCountFormatterCountStyleBinary in countStyle.

NSByteCountFormatterCountStyleFile: Specifies display of file or storage byte counts. The actual behavior for this is platform-specific; on OS X 10.8, this uses the decimal style, but that may change over time.

NSByteCountFormatterCountStyleMemory: Specifies display of memory byte counts. The actual behavior for this is platform-specific; on OS X 10.8, this uses the binary style, but that may change over time.

NSByteCountFormatterCountStyleDecimal: Specifies the number of bytes for KB explicitly, 1000 bytes are shown as 1 KB

NSByteCountFormatterCountStyleBinary: Specifies the number of bytes for KB explicitly, 1024 bytes are shown as 1 KB

Modern Objective-c syntext:

- (id)transformedValue:(id)value
{

    double convertedValue = [value doubleValue];
    int multiplyFactor = 0;

    NSArray *tokens = @[@"bytes",@"KB",@"MB",@"GB",@"TB",@“PB”, @“EB”, @“ZB”, @“YB”];

    while (convertedValue > 1024) {
        convertedValue /= 1024;
        multiplyFactor++;
    }

    return [NSString stringWithFormat:@"%4.2f %@",convertedValue, tokens[multiplyFactor]];
}