计算器:按下“Enter”按钮后,运行时应用程序崩溃

时间:2012-03-05 22:45:12

标签: ios xcode

我写了一个计算器程序编译得很好,但是当我点击“Enter”按钮时崩溃了。

以下是崩溃日志:

2012-03-05 14:35:46.561 Calculator[35699:f803] -[CalculatorViewController enterPressed:]: unrecognized selector sent to instance 0x6a590f0
2012-03-05 14:35:46.657 Calculator[35699:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CalculatorViewController enterPressed:]: unrecognized selector sent to instance 0x6a590f0'
*** First throw call stack:
(0x13bb052 0x154cd0a 0x13bcced 0x1321f00 0x1321ce2 0x13bcec9 0x155c2 0x1555a 0xbab76 0xbb03f 0xba2fe 0x3aa30 0x3ac56 0x21384 0x14aa9 0x12a5fa9 0x138f1c5 0x12f4022 0x12f290a 0x12f1db4 0x12f1ccb 0x12a4879 0x12a493e 0x12a9b 0x20fd 0x2065)
terminate called throwing an exception(lldb) 

视图控制器的实现:

#import "CalculatorViewController.h"
#import "CalculatorBrain.h"

@interface CalculatorViewController ()
@property (nonatomic) BOOL userIsInTheMiddleOfEnteringANumber;
@property (nonatomic, strong) CalculatorBrain *brain;
@end

@implementation CalculatorViewController
@synthesize display = _display;
@synthesize userIsInTheMiddleOfEnteringANumber = _userIsInTheMiddleOfEnteringANumber;
@synthesize brain = _brain;

- (CalculatorBrain *)brain
{
    if(!_brain) _brain = [[CalculatorBrain alloc] init];
    return _brain;
}

- (IBAction)digitPressed:(UIButton *)sender 
{
    NSString *digit = [sender currentTitle];
    if (self.userIsInTheMiddleOfEnteringANumber) {
        self.display.text = [self.display.text stringByAppendingString:digit];
    } else {
        self.display.text = digit;
        self.userIsInTheMiddleOfEnteringANumber = YES;
    }

}

- (IBAction)enterPressed 
{
    [self.brain pushOperand:[self.display.text doubleValue]];
    self.userIsInTheMiddleOfEnteringANumber = NO;
}

- (IBAction)operationPressed:(UIButton *)sender 
{
    if(self.userIsInTheMiddleOfEnteringANumber) {
        [self enterPressed];
    }
    NSString *operation = sender.currentTitle;
    double result = [self.brain performOperation:operation];
    self.display.text = [NSString stringWithFormat:@"%g",result];
}

@end

1 个答案:

答案 0 :(得分:3)

答案在于错误消息-[CalculatorViewController enterPressed:],该消息表明发送到视图控制器的选择器应该采用参数。但是,您已定义enterPressed而没有任何参数。 enterPressed方法应该更像operationPressed:,即:

- (IBAction) enterPressed:(UIButton *)sender