我是 100% 的新手iOS
。我正在在线观看斯坦福大学的视频来学习iOS
。我花了几个小时慢慢浏览第二个视频,小心翼翼地确保我没有在一行代码上犯错。一切都很完美,直到 - 你不知道 - 编码的最后一分钟。
我和我的妻子花了很多时间试图弄清楚,但我的代码与教授的代码相符。请帮我。我喜欢通过这些视频进行学习,但在我具备此功能并花时间复习之前,我无法继续前进。
#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:(id)sender
{
if (self.userIsInTheMiddleOfEnteringANumber) [self enterPressed];
double result = [self.brain performOperation:sender.currentTitle]; // <- HERE IS THE LINE IN QUESTION
NSString *resultString = [NSString stringWithFormat:@"%g", result];
self.display.text = resultString;
}
@end
CalculatorBrain.m
#import "CalculatorBrain.h"
@interface CalculatorBrain()
@property (nonatomic, strong) NSMutableArray *operandStack;
@end
@implementation CalculatorBrain
@synthesize operandStack = _operandStack;
- (NSMutableArray *) operandStack
{
if (_operandStack == nil) _operandStack = [[NSMutableArray alloc] init];
return _operandStack;
}
- (void)pushOperand:(double)operand
{
[self.operandStack addObject:[NSNumber numberWithDouble:operand]];
}
- (double)popOperand
{
NSNumber *operandObject = [self.operandStack lastObject];
if (operandObject) [self.operandStack removeLastObject];
return [operandObject doubleValue];
}
- (double)performOperation:(NSString *)operation
{
double result = 0;
if ([operation isEqualToString:@"+"])
{
result = [self popOperand] + [self popOperand];
}
else if ([@"*" isEqualToString:operation])
{
result = [self popOperand] * [self popOperand];
}
[self pushOperand:result];
return result;
}
@end