简体   繁体   中英

Calculator: Getting runtime app crash when “Enter” button is pressed

I have written a calculator program which compiles fine, but crashes when I hit the "Enter" button.

Here is the crash log:

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) 

Implementation of view controller:

#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

The answer lies in the error message -[CalculatorViewController enterPressed:] which says that the selector sent to the view controller is expected to take a parameter. However you have defined enterPressed without any parameters. The enterPressed method should look more like operationPressed: ie:

- (IBAction) enterPressed:(UIButton *)sender 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM