ローマ数字モードの電卓を作っています。モデルビューとビューコントローラーで操作を実行しました。私の問題は、ローマ数字を NSNumber に変換する必要があることです。UILabel があり、View Controller はラベルにあるものを取得し、それをモデル ビューのオペランドとして設定します。ラベルからローマ数字を取得して NSNumber にする方法を知っている人はいますか? ここにいくつかのコードがあります:
- (IBAction)digitPressed:(UIButton *)sender {
NSString *digit = [[sender titleLabel] text];
if (self.userIsTypingNumber) {
[self.display setText:[self.display.text stringByAppendingString:digit]];
} else {
[self.display setText:digit];
self.userIsTypingNumber = YES;
}
}
- (IBAction)operationPressed:(UIButton *)sender {
if (self.userIsTypingNumber) {
if ([self isValidForRoman:self.display.text] == YES) {
//find out what roman numeral is in the display
} else {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
[numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
NSNumber *n = [numberFormatter numberFromString:self.display.text];
[[Model singleton] setOperand:n];
self.userIsTypingNumber = NO;
}
}
NSString *operation = [[sender titleLabel] text];
NSNumber *result = [[Model singleton] performOperation:operation];
[self.display setText:[NSString stringWithFormat:@"%@", result]];
}
- (IBAction)clearDigitPressed:(UIButton *)sender {
[self.display setText:@""];
}
- (IBAction)clearOperationPressed:(UIButton *)sender {
[[Model singleton] performOperation:nil];
[self.display setText:@""];
}
- (IBAction)changeNumeralType:(id)sender {
switch ([sender selectedSegmentIndex]) {
case 0:
{
[self.button1 setTitle:@"1" forState:UIControlStateNormal];
[self.button2 setTitle:@"2" forState:UIControlStateNormal];
[self.button3 setTitle:@"3" forState:UIControlStateNormal];
[self.button4 setTitle:@"4" forState:UIControlStateNormal];
[self.button5 setTitle:@"5" forState:UIControlStateNormal];
[self.button6 setTitle:@"6" forState:UIControlStateNormal];
[self.button7 setTitle:@"7" forState:UIControlStateNormal];
[self.button8 setTitle:@"8" forState:UIControlStateNormal];
[self.button9 setTitle:@"9" forState:UIControlStateNormal];
[self.button0 setTitle:@"0" forState:UIControlStateNormal];
} break;
case 1:
{
[self.button1 setTitle:@"L" forState:UIControlStateNormal];
[self.button2 setTitle:@"C" forState:UIControlStateNormal];
[self.button3 setTitle:@"D" forState:UIControlStateNormal];
[self.button4 setTitle:@"I" forState:UIControlStateNormal];
[self.button5 setTitle:@"V" forState:UIControlStateNormal];
[self.button6 setTitle:@"X" forState:UIControlStateNormal];
[self.button7 setTitle:@"" forState:UIControlStateNormal];
[self.button8 setTitle:@"" forState:UIControlStateNormal];
[self.button9 setTitle:@"" forState:UIControlStateNormal];
[self.button0 setTitle:@"M" forState:UIControlStateNormal];
} break;
}
}
- (BOOL)isValidForRoman:(NSString *)text
{
NSString *romanRegex = @"^(?=.)(?i)M*(D?C{0,3}|C[DM])(L?X{0,3}|X[LC])(V?I{0,3}|I[VX])$";
NSPredicate *romanTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", romanRegex];
return ([romanTest evaluateWithObject:text]);
}