-1

我正在尝试制作一个计算器应用程序,但是当我按下回车键时,没有任何东西被推入数组。我有一个定义方法的类CaculatorBrain,但是(现在)我在视图控制器中pushElement定义并实现了方法。pushElement

当我按下输入键时在控制台中键入操作数对象时,数组的内容为零!这是为什么?

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

@interface CalculatorViewController ()
@property (nonatomic)BOOL userIntheMiddleOfEnteringText;
@property(nonatomic,copy) NSMutableArray* operandStack;


@end

@implementation CalculatorViewController

BOOL userIntheMiddleOfEnteringText;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}


-(NSMutableArray*) operandStack {
    if (_operandStack==nil) {
        _operandStack=[[NSMutableArray alloc]init];
    }
    return _operandStack;


}



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



- (IBAction)digitPressed:(UIButton*)sender {
    if (self.userIntheMiddleOfEnteringText) {
    NSString *digit= [sender currentTitle];
    NSString *currentDisplayText=self.display.text;
    NSString *newDisplayText= [currentDisplayText stringByAppendingString:digit];
    self.display.text=newDisplayText;
     NSLog(@"IAm in digitPressed method");
}
    else
    {
        NSString *digit=[sender currentTitle];
        self.display.text = digit;
       self. userIntheMiddleOfEnteringText=YES;
    }
}


-(void)pushElement:(double)operand {
    NSNumber *operandObject=[NSNumber numberWithDouble:operand];
    [_operandStack addObject:operandObject];
    NSLog(@"operandObject is %@",operandObject);
    NSLog(@"array contents is %@",_operandStack);

}


- (IBAction)enterPressed {

[self  pushElement: [self.display.text doubleValue] ];

NSLog(@"the contents of array is %@",_operandStack);

        userIntheMiddleOfEnteringText= NO;

}
4

1 回答 1

0

看起来操作数堆栈从未初始化。

当您直接访问时_operandStack,您不会经过-(NSMutableArray*) operandStack,这是分配和初始化操作数堆栈的唯一地方。如果未分配数组,则不能在其中放入任何内容,这就是将内容记录为 nil 的原因。

我建议在方法内部以外的任何地方都使用self.operandStack(它使用检查是否_operandStack为 nil 的-(NSMutableArray*) operandStack方法),或者在viewDidLoad.

于 2013-03-05T18:38:55.997 回答