Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objective-c file size formatter

Is there build in methods for formatting file sizes in Objective C? Or may be you could suggest me some library/source code/etc.?

What I mean is you have some file size that should be displayed something like this depending on given size:

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

Thanks in advance

like image 582
Pan.Krutilkin Avatar asked May 15 '12 19:05

Pan.Krutilkin


People also ask

How do I get the size of a file in Objective C?

unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:someFilePath error:nil] fileSize]; This returns the file size in Bytes. I like this one.

How do I check the size of a file in swift 5?

You can call . fileSize() on attr to get file size.


1 Answers

This one solves the problem quite elegantly:

[NSByteCountFormatter stringFromByteCount:countStyle:]

Example usage:

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:

Display file size: 14.4 MB
Display file size: 50 KB

The output will be formatted properly according to the device's regional settings.

Available since iOS 6.0 and OS X 10.8.

like image 72
Michael Thiel Avatar answered Oct 02 '22 09:10

Michael Thiel