我对objective-c完全陌生,所以我不知道为什么会这样。我仍在努力思考这些概念,但我不知道我在寻找什么,所以我希望你们中的一个好人,聪明的人可以帮助我。我确定这是我没有意识到的愚蠢的问题。
视图控制器.h:
#import <UIKit/UIKit.h>
#import "CalculatorBrain.h"
@interface ViewController : UIViewController {
IBOutlet UILabel *display;
CalculatorBrain *brain;
BOOL userIsInTheMiddleOfTypingANumber;
}
- (IBAction)digitPressed:(UIButton *)sender;
- (IBAction)operationPressed:(UIButton *)sender;
@end
ViewController.m:(在“NSString *operation = [[sender titleLabel] text];”接近尾声时发生崩溃)
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (CalculatorBrain *)brain
{
if (brain) {
brain = [[CalculatorBrain alloc] init];
}
return brain;
}
- (IBAction)digitPressed:(UIButton *)sender
{
NSString *digit = [[sender titleLabel] text];
if (userIsInTheMiddleOfTypingANumber) {
[display setText:[[display text] stringByAppendingString:digit]];
} else {
[display setText:digit];
userIsInTheMiddleOfTypingANumber = YES;
}
}
- (IBAction)operationPressed:(UIButton *)sender
{
if (userIsInTheMiddleOfTypingANumber) {
[[self brain] setOperand:[[display text] doubleValue]];
userIsInTheMiddleOfTypingANumber = NO;
}
NSString *operation = [[sender titleLabel] text];
double result = [[self brain] performOperation:operation];
[display setText:[NSString stringWithFormat:@"%g", result]];
}
@end
计算器大脑.h:
#import <Foundation/Foundation.h>
@interface CalculatorBrain : NSObject {
double operand;
NSString *waitingOperation;
double waitingOperand;
}
- (void)setOperand:(double)anOperand;
- (double)performOperation:(NSString *)operation;
@end
计算器大脑.m:
#import "CalculatorBrain.h"
@implementation CalculatorBrain
- (void)setOperand:(double)anOperand
{
operand = anOperand;
}
- (void)performWaitingOperation
{
if ([@"+" isEqual:waitingOperation]) {
operand = waitingOperand + operand;
} else if ([@"-" isEqual:waitingOperation]) {
operand = waitingOperand - operand;
} else if ([@"*" isEqual:waitingOperation]) {
operand = waitingOperand * operand;
} else if ([@"/" isEqual:waitingOperation]) {
if (operand) {
operand = waitingOperand / operand;
}
}
}
- (double)performOperation:(NSString *)operation
{
if ([operation isEqual:@"sqrt"]) {
operand = sqrt(operand);
} else {
[self performWaitingOperation];
waitingOperation = operation;
waitingOperand = operand;
}
return operand;
}
@end
提前感谢任何帮助或提示......我不知道我在做什么:)