我正在做一个基于在线教程itunes.apple的计算器应用程序。 com / itunes-u / ipad-iphone-application-development / id473757255(tut 2)
我密切关注每一步,一切都很好,直到方法调用performOperation的完成步骤。当我构建并运行时,数字和输入函数工作正常。只有操作方法不起作用。所以我认为主要的麻烦在于操作方法。
BrainCalculator.h
@interface CalculatorBrain : NSObject
-(void) pushOperand: (double)operand;
-(double) performOperation: (NSString*) operation;
@end
BrainCalculator.m
#import "CalculatorBrain.h"
@interface CalculatorBrain()
@property (nonatomic, strong) NSMutableArray* _operandStack;
@end
@implementation CalculatorBrain
@synthesize _operandStack;
-(NSMutableArray *)operandStack
{
if (!_operandStack){
_operandStack= [[NSMutableArray alloc ]init];
}
return _operandStack;
}
-(void)pushOperand:(double)operand{
NSNumber *operandObject = [NSNumber numberWithDouble:operand];
[self.operandStack addObject:operandObject];
}
-(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];
}else if ([operation isEqualToString:@"-"]){
double subtrahend = [self popOperand];
result = [self popOperand] - subtrahend;
}else if( [operation isEqualToString:@"/"]){
double divisor = [self popOperand];
if (divisor) result = [self popOperand] / divisor;
}
[self pushOperand:result];
return result;
}
@end
最初,在我看来,performOperation方法非常腥,所以我试着摆弄
}else if ([@"*" isEqualToString:operation]){
到
}else if ([operation isEqualToString:@"*"]){
希望它能起作用,但遗憾的是它没有。
仅供参考
viewcontroller.m
#import "CalculatorViewController.h"
#import "CalculatorBrain.h"
@interface CalculatorViewController ()
@property (nonatomic) BOOL userIsInTheMiddleOfEnteringANumber;
@property (nonatomic, strong) CalculatorBrain *brain;
@end
@implementation CalculatorViewController
@synthesize display;
@synthesize userIsInTheMiddleOfEnteringANumber;
@synthesize brain= _brain;
-(CalculatorBrain*)brain
{
if(!_brain)_brain = [[CalculatorBrain alloc]init];
return _brain;
}
- (IBAction)digitPressed:(UIButton *)sender {
NSString * digit= [ sender currentTitle];
if (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
帮助将非常感激,因为我正在练习xcode为我最后一年的重大项目做好准备。