首页 > 代码库 > [Stanford] RPN Calculator(controller)

[Stanford] RPN Calculator(controller)

CalculatorViewController.h

//iOS> Application > Single View Application 建立一个模板controller和空白View#import <UIKit/UIKit.h>@interface CalculatorViewController : UIViewController@property (weak, nonatomic) IBOutlet UILabel *display;          //display------label的,view到controller的outlet@end                              //为什么用weak指针?因为label在这个窗口上,这个父窗口View已经有个strong指针指向它了 ,                                     //如果窗口没有strong指针指向它,那我也不需要label了,因为窗口都没了label也没了.                                   //所以我只需要weak指针,我只需要它在View里,通常Outlet都是weak的

CalculatorViewController.m

#import "CalculatorViewController.h"#import "CalculatorBrain.h"@interface CalculatorViewController()@property (nonatomic) BOOL userIsInTheMiddleOfEnteringANumber; //初始值是0,属于private@property (nonatomic ,strong)CalculatorBrain *brain;@end @implementation CalculatorViewController@synthesize display=_display;                                         //display------label的名字,view到controller的outlet,@synthesize userIsInTheMiddleOfEnteringANumber=_userIsInTheMiddleOfEnteringANumber;@synthesize brain=_brain;-(CalculatorBrain *)brain{    if (!_brain) _brain=[[CalculatorBrain alloc]init];        //Lazy instantiation         return _brain;}- (IBAction)digitPressed:(UIButton *)sender                       //digitPressed------Round Rect Button的,target action。                                                                   //当按钮被按,view发消息给controller,消息附带参数,参数是发送者自己,这里就是按钮 {                                                                 //本函数作用-------按下按钮,label变化.       NSString *digit=sender.currentTitle;   //也是property所以可以也应该用.号(此处是复制了NSString还是给了个                                                          //指针指向NSString?依这个property的声明而定,若property是strong的则是复制)     if(self.userIsInTheMiddleOfEnteringANumber)       {         self.display.text=[self.display.text stringByAppendingString:digit];     }    else     {        self.display.text=digit;                    //property的getter方法可以用.号,获取值的方法是发getter到self的Label          self.userIsInTheMiddleOfEnteringANumber=1;        }}- (IBAction)OperationPressed:(UIButton *)sender{            if(self.userIsInTheMiddleOfEnteringANumber)[self enterPressed]; //"6 enter 3 enter +"   VS   "6  enter 3 +"           double result=[self.brain performOperation:sender.currentTitle];           NSString *resultString=[NSString stringWithFormat:@"%g",result];           self.display.text=resultString;}- (IBAction)enterPressed    //把操作数入栈到model里,需要一个指向model的指针。所以几乎每个controller  {                                            //都有这么一个private的property,strong的,而且还需要synthesize。         [self.brain pushOperand:[self.display.text doubleValue]];             self.userIsInTheMiddleOfEnteringANumber=0;    }@end

 

[Stanford] RPN Calculator(controller)