2013-03-04 73 views
-1

我試圖製作一個計算器應用程序,但是當我按下輸入時,沒有任何內容被推入數組中。我有一個名爲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; 

} 
+1

它看起來像你從來沒有實際初始化operandStack - 你使用的是支持它的變量('_operandStack')。嘗試把你的操作數堆棧分配/初始化放在'viewDidLoad'中。 – thegrinner 2013-03-04 21:36:59

+0

確實,你爲什麼在'-operandStack'之外的任何地方使用'_operandStack'而不是'self.operandStack'?另外,爲什麼該屬性標記爲'copy'而不是'strong'(或'retain')? – Caleb 2013-03-04 21:40:30

+0

self.operandStack而不是_operandStack確實解決了這個問題,但我很困惑,我的理解是_operandStack和self.operandStack都是作爲xcode爲我合成operandStack的相同目的的含義,所以self.operandStack或_operandStack都可以使用?你可以幫我解釋爲什麼self.operandStack解決問題 – Dina 2013-03-05 16:11:29

回答

0

它看起來像操作數棧從未初始化。

當您直接訪問_operandStack時,您不會通過-(NSMutableArray*) operandStack,這是操作數堆棧分配和初始化的唯一地方。如果數組未分配,則不能放入任何內容,這就是爲什麼它將內容記錄爲零的原因。

我會建議您使用self.operandStack(使用來檢查,如果_operandStack爲零的方法),除了隨處可見的-(NSMutableArray*) operandStack方法,或在您的viewDidLoad分配操作數棧內。

+0

感謝您的回答... – Dina 2013-03-06 16:30:16