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:
Thanks in advance
unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:someFilePath error:nil] fileSize]; This returns the file size in Bytes. I like this one.
You can call . fileSize() on attr to get file size.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With