, , IMO, , , ( , . Model-View-Controller). , , NSNumber , ββ?
, , , . "unitsType", , .
, , MDFileSizeFormatter, :
#import <Foundation/Foundation.h>
enum {
MDVolumeFormatterMetricUnitsType = 1,
MDVolumeFormatterOurStupidAmericanUnitsType = 2,
MDVolumeFormatterDefaultUnitsType = MDVolumeFormatterMetricUnitsType
};
typedef NSUInteger MDVolumeFormatterUnitsType;
@interface MDVolumeFormatter : NSFormatter {
MDVolumeFormatterUnitsType unitsType;
NSNumberFormatter *numberFormatter;
}
- (id)initWithUnitsType:(MDVolumeFormatterUnitsType)aUnitsType;
@property (assign) MDVolumeFormatterUnitsType unitsType;
@end
.m:
#import "MDVolumeFormatter.h"
#define MILLILITERS_PER_OUNCE 29.5735296
@implementation MDVolumeFormatter
@synthesize unitsType;
- (id)init {
return [self initWithUnitsType:MDVolumeFormatterDefaultUnitsType];
}
- (id)initWithUnitsType:(MDVolumeFormatterUnitsType)aUnitsType {
if (self = [super init]) {
numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormat:@"#,###.#"];
[self setUnitsType:aUnitsType];
}
return self;
}
- (void)dealloc {
[numberFormatter release];
[super dealloc];
}
- (NSString *)stringForObjectValue:(id)anObject {
if ([anObject isKindOfClass:[NSNumber class]]) {
NSString *string = nil;
if (unitsType == MDVolumeFormatterMetricUnitsType) {
string = [[numberFormatter stringForObjectValue:
[NSNumber numberWithFloat:
[(NSNumber *)anObject floatValue] * MILLILITERS_PER_OUNCE]]
stringByAppendingString:@" mL"];
} else {
string = [[numberFormatter stringForObjectValue:anObject] stringByAppendingString:@" oz"];
}
return string;
}
return nil;
}
@end
. , floatValue 16.0, , "2.0 " 16 .