Bytes to KiloBytes

久未见 提交于 2019-12-06 10:15:44

问题


I am retrieving the size of all files in the document directory. I am using the method attributesOfItemAtPath to do so. It is successful. But I am getting the output in the form of bytes and of class NSNumber. It does'nt look good.

So, I need to get the output in KBs or MBs and I have to convert them into NSString in order to store that in a NSDictionary as I have to display it in a TableView. Please help me to do so. Thank you.

Here is my code..

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

And I am using the following code to bind the size in tableView which is not working.

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

Help me to convert the size of a file from byte to KiloByte and to display it in a tableView. Thank you in advance..


回答1:


Rounded to the nearest KB:

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



回答2:


You can use my NSValueTransformer subclass if you like:

@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



回答3:


Consider using NSNumber instead of NSString to store numbers in an NSDictionary.



来源:https://stackoverflow.com/questions/4195419/bytes-to-kilobytes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!