我試圖製作一個計算器應用程序,但是當我按下輸入時,沒有任何內容被推入數組中。我有一個名爲CaculatorBrain
的類,其中pushElement
方法已定義,但是(現在)我在視圖控制器中定義並實現pushElement
方法。計算器應用程序不會將操作數添加到陣列
當我輸入操作數對象時,如果按下enter按鈕時,操作數對象的內容爲零!這是爲什麼?
#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;
}
它看起來像你從來沒有實際初始化operandStack - 你使用的是支持它的變量('_operandStack')。嘗試把你的操作數堆棧分配/初始化放在'viewDidLoad'中。 – thegrinner 2013-03-04 21:36:59
確實,你爲什麼在'-operandStack'之外的任何地方使用'_operandStack'而不是'self.operandStack'?另外,爲什麼該屬性標記爲'copy'而不是'strong'(或'retain')? – Caleb 2013-03-04 21:40:30
self.operandStack而不是_operandStack確實解決了這個問題,但我很困惑,我的理解是_operandStack和self.operandStack都是作爲xcode爲我合成operandStack的相同目的的含義,所以self.operandStack或_operandStack都可以使用?你可以幫我解釋爲什麼self.operandStack解決問題 – Dina 2013-03-05 16:11:29