Objective-c format file format

Are there any built-in methods for formatting file sizes in Objective-C? Or maybe you could offer me some kind of library / source code, etc.?

I mean, you have a file size that should display something like this: depending on the given size:

  • 1234 kb
  • 1,2 mb
  • etc..

Thanks in advance

+3
source share
3 answers

This question solves the problem quite elegantly:

[NSByteCountFormatter stringFromByteCount:countStyle:]

Usage example:

long long fileSize = 14378165;
NSString *displayFileSize = [NSByteCountFormatter stringFromByteCount:fileSize
                                                           countStyle:NSByteCountFormatterCountStyleFile];
NSLog(@"Display file size: %@", displayFileSize);

fileSize = 50291;
displayFileSize = [NSByteCountFormatter stringFromByteCount:fileSize
                                                 countStyle:NSByteCountFormatterCountStyleFile];
NSLog(@"Display file size: %@", displayFileSize);

Log output:

File size: 14.4 MB
Show file size: 50 KB

The output will be formatted correctly according to the regional settings of the device.

Available with iOS 6.0 and OS X 10.8.

+6
source

, , kb mb

NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:URL error:&attributesError];

NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
long long fileSize = [fileSizeNumber longLongValue];



Then conversion table

    1 byte = 8 bits

    1 KiB = 1,024 bytes

    1 MiB = 1024  kb

    1 GiB = 1024  mb

0

Here is the code that I found lay. Not very efficient and probably better tied to the NSNumberFormatter category than NSNumber, and so on, but it seems to work

@interface NSNumber (FormatKibi)
- (NSString *)formatKibi;
@end

@implementation NSNumber (FormatKibi)
- (NSString *)formatKibi {
  double value = [self doubleValue];
  static const char suffixes[] = { 0, 'k', 'm', 'g', 't' }; 
  int suffix = 0;
  if (value <= 10000)
    return [[NSString stringWithFormat:@"%5f", value] 
         substringToIndex:5];
  while (value > 9999) {
    value /= 1024.0;
    ++suffix;
    if (suffix >= sizeof(suffixes)) return @"!!!!!";
  }
  return [[[NSString stringWithFormat:@"%4f", value] 
            substringToIndex:4]
           stringByAppendingFormat:@"%c", suffixes[suffix]];
}
@end

I tested this with this:

int main(int argc, char *argv[]) {
  for (int i = 1; i != argc; ++i) {
    NSNumber *n = [NSNumber numberWithInteger:
                              [[NSString stringWithUTF8String:argv[i]]
                                integerValue]];
    printf("%s ", [[n formatKibi] UTF8String]);
  }
  printf("\n");
  return 0;
}

Then:

$ ./sizeformat 1 12 123 1234 12345 123456 1234567 12345678 1234567890 123456789012 12345678901234 1234567890123456 123456789012345678
1.000 12.00 123.0 1234. 12.0k 120.k 1205k 11.7m 1177m 114.g 11.2t 1122t !!!!!
0
source

All Articles