1. 程式人生 > >ios 學習之 Simple Calculator Application

ios 學習之 Simple Calculator Application

//
//  ViewController.h
//  ocTest
//
//  Created by Hu Li on 2018/12/30.
//  Copyright © 2018 Hu Li. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{
    
    bool operatorPressed;
    bool add;
    NSString *firstEntry;
    NSString *secondEntry;
    
}

@property (weak, nonatomic) IBOutlet UILabel *labelOutput;

- (IBAction)clearPressed:(id)sender;
- (IBAction)addPressed:(id)sender;
- (IBAction)minusPressed:(id)sender;
- (IBAction)equalsPressed:(id)sender;

- (IBAction)numberPressed:(UIButton*)sender;

@end

  

//
//  ViewController.m
//  ocTest
//
//  Created by Hu Li on 2018/12/30.
//  Copyright © 2018 Hu Li. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

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


- (IBAction)clearPressed:(id)sender {
    operatorPressed = FALSE;
     _labelOutput.text = nil;
    firstEntry = nil;
    secondEntry = nil;
    
}

- (IBAction)addPressed:(id)sender {
    add=TRUE;
    operatorPressed =TRUE;
}

- (IBAction)minusPressed:(id)sender {
    add=FALSE;
    operatorPressed =TRUE;
}

- (IBAction)equalsPressed:(id)sender {
    if(add == FALSE){
        int outPut = [firstEntry intValue] - [secondEntry intValue];
        _labelOutput.text = [NSString stringWithFormat: @"%i", outPut];
    }else{
        int outPut = [firstEntry intValue] + [secondEntry intValue];
        _labelOutput.text = [NSString stringWithFormat: @"%i", outPut];
        
    }
    operatorPressed = FALSE;
    firstEntry = nil;
    secondEntry = nil;
}
- (IBAction)numberPressed:(UIButton*)sender{
    NSInteger tag = sender.tag;
    if(operatorPressed ==FALSE){
        if(firstEntry == NULL){
            firstEntry = [NSString stringWithFormat:@"%i",(long)tag];
            _labelOutput.text = firstEntry;
        }else{
            firstEntry = [NSString stringWithFormat:@"%@%i",firstEntry,tag];
            _labelOutput.text = firstEntry;
        }
    }else{
        if(secondEntry == NULL){
            secondEntry = [NSString stringWithFormat:@"%i",tag];
            _labelOutput.text = secondEntry;
        }else{
            secondEntry = [NSString stringWithFormat:@"%@%i",secondEntry,tag];
            _labelOutput.text = secondEntry;
        }
    }
}
@end  

學習總結:

1. nil 和null?

2.Values of type 'NSInteger' should not be used as format arguments; add an explicit cast to 'long' instead。