File size in Snow Leopard

前端 未结 4 1028
说谎
说谎 2021-02-11 08:30

I\'m trying to figure out how to convert a file\'s (or directory\'s) byte size into kilobytes, megabytes, gigabytes, etc... respectively according the file\'s or directory\'s si

4条回答
  •  难免孤独
    2021-02-11 09:01

    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
    

提交回复
热议问题