字节到KiloBytes

时间:2010-11-16 14:52:20

标签: iphone filesize

我正在检索文档目录中所有文件的大小。我使用方法attributesOfItemAtPath来执行此操作。它很成功。但我得到的是字节和类NSNumber形式的输出。它看起来不太好。

所以,我需要以KB或MB的形式获取输出,我必须将它们转换为NSString,以便将其存储在NSDictionary中,因为我必须在TableView中显示它。请帮我这样做。谢谢。

这是我的代码..

directoryContent = [[NSMutableArray alloc] init];
    for (NSString *path in paths){
filesDictionary  =[[NSMutableDictionary alloc] init];
filesSize = [[NSNumber alloc] init]; 
filesSize = [filesDictionary objectForKey:NSFileSize];
filesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:filesSize, @"filesSize", nil];
[directoryContent addObject:[filesDictionary copy]];
}

我正在使用以下代码绑定tableView中无法正常工作的大小。

cell.lblSize.text = (NSString *) [[directoryContent objectAtIndex:listIndex] objectForKey:@"filesSize"];

帮我将文件大小从byte转换为KiloByte并将其显示在tableView中。 提前谢谢..

3 个答案:

答案 0 :(得分:8)

如果您愿意,可以使用我的NSValueTransformer子类:

@interface FileSizeTransformer : NSValueTransformer {

}

+ (Class)transformedValueClass;
+ (BOOL)allowsReverseTransformation;
- (id)transformedValue:(id)value;

@end

@implementation FileSizeTransformer
+ (Class)transformedValueClass;
{
    return [NSString class];
}

+ (BOOL)allowsReverseTransformation;
{
    return NO;
}
- (id)transformedValue:(id)value;
{
    if (![value isKindOfClass:[NSNumber class]])
        return nil;

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

    NSArray *tokens = [NSArray arrayWithObjects:@"B",@"KB",@"MB",@"GB",@"TB",nil];

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

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

@end

答案 1 :(得分:5)

舍入到最近的KB:

NSNumber *fileSize = [[directoryContent objectAtIndex:listIndex]
                      objectForKey:@"fileSize"];
cell.lblSize.text = [NSString stringWithFormat: @"%d",
                     (int)round([fileSize doubleValue] / 1024]);

答案 2 :(得分:0)

考虑使用NSNumber代替NSStringNSDictionary中存储数字。

相关问题