字节到KiloBytes

iOS*_*iOS 2 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]];
}
Run Code Online (Sandbox Code Playgroud)

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

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

帮我将文件大小从byte转换为KiloByte并将其显示在tableView中.先感谢您..

die*_*ikh 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
Run Code Online (Sandbox Code Playgroud)


Dan*_*son 5

舍入到最近的KB:

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