objective-c – 如何正确获取文件大小,并将其转换为MB,GB在Cocoa?

objective-c – 如何正确获取文件大小,并将其转换为MB,GB在Cocoa?,第1张

概述Possible Duplicate: 07000 我是新来的可可。我试图正确获取文件夹文件的大小。如果它少于1 GB或以GB为单位,则以MB为单位显示。 我想要显示的方式是一个数字后点。 例 如果大于1000则为5.5MB> 1.1 GB 我试图使用这个 unsigned long long size= ([[[NSFileManager defaultManager] attributesO

Possible Duplicate:
07000

我是新来的可可。我试图正确获取文件夹文件的大小。如果它少于1 GB或以GB为单位,则以MB为单位显示。

我想要显示的方式是一个数字后点。


如果大于1000则为5.5MB> 1.1 GB

我试图使用这个

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

但我不能正确转换数字,并显示它,因为我想要的。

谢谢。

解决方法 为了将文件大小转换为MB,Gb使用以下函数

- (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]];}

编辑:

你也可以使用NSByteCountFormatter类。适用于iOS 6.0 / OS X v10.8及更高版本。

[NSByteCountFormatter stringFromByteCount:1999 countStyle:NSByteCountFormatterCountStylefile];

您可以在countStyle中使用NSByteCountFormatterCountStylefile,NSByteCountFormatterCountStyleMemory,NSByteCountFormatterCountStyleDecimal或NSByteCountFormatterCountStyleBinary。

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

现代Objective-c语法:

- (ID)transformedValue:(ID)value{    double convertedValue = [value doubleValue];    int multiplyFactor = 0;    NSArray *tokens = @[@"bytes",@“YB”];    while (convertedValue > 1024) {        convertedValue /= 1024;        multiplyFactor++;    }    return [Nsstring stringWithFormat:@"%4.2f %@",tokens[multiplyFactor]];}
总结

以上是内存溢出为你收集整理的objective-c – 如何正确获取文件大小,并将其转换为MB,GB在Cocoa?全部内容,希望文章能够帮你解决objective-c – 如何正确获取文件大小,并将其转换为MB,GB在Cocoa?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1044566.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-24
下一篇2022-05-24

发表评论

登录后才能评论

评论列表(0条)

    保存