这里是 Obj-C 的新手 :) 我正在编写一个转换数字的代码(主要是为了控制点后的零,5.000 -> 5 或 5.00)。所以,我让它工作,但我真的想创建一个类来根据需要使用它。这是工作代码:
主视图控制器.h
currentNumber = currentNumber *10 + (float)[sender tag];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:2];
[formatter setMinimumFractionDigits:0];
NSString *convertedNumber = [formatter stringFromNumber:[NSNumber numberWithFloat:currentNumber]];
calculatorScreen.text = [NSString stringWithFormat:@"%@",convertedNumber];
所以,我只想创建一个类来为我做这件事并返回转换后的数字。这是我所做的:
格式编号.h
@interface FormatNumber: NSNumber
{
NSString *nf;
}
- (void) getNumber:(float)n1;
- (NSString *) retNumber;
@end
格式编号.m
@implementation FormatNumber;
-(void) getNumber:(float)n1
{
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:2];
[formatter setMinimumFractionDigits:0];
nf = [formatter stringFromNumber:[NSNumber numberWithFloat: n1]];
}
-(NSString *) retNumber; // As I cannot return something from void, I tried to do this way, don't know if it's the better
{
return nf;
}
@end
MainViewController.h(试图传递并从类中获取值)
currentNumber = currentNumber *10 + (float)[sender tag];
NSString *convertedNumber = 0;
FormatNumber *n1 = [[FormatNumber alloc] init];
[FormatNumber getNumber:currentNumber]; // No known class method for selector 'getNumber'
convertedNumber = [FormatNumber retNumber]; // No known class method for selector 'retNumber'
calculatorScreen.text = [NSString stringWithFormat:@"%@",convertedNumber];
另外,如果有一种简单的方法可以编写此代码,我将不胜感激:)