I'm taking the lectures of Stanford's iPhone application development and the first assignment is to build a RPN calculator.
I'm having an issue that is probably something simple that I'm missing out.
There is a model class, called CalculatorBrain:
.h
#import <Foundation/Foundation.h>
@interface CalculatorBrain : NSObject
- (void)pushOperand:(double)operand;
- (double)performOperation:(NSString *)operation;
@property (nonatomic, strong) NSMutableArray *operandStack;
@end
.m
#import "CalculatorBrain.h"
@interface CalculatorBrain()
@end
@implementation CalculatorBrain
@synthesize operandStack = _operandStack;
- (NSMutableArray *)operandStack
{
if (!_operandStack) {
_operandStack = [[NSMutableArray alloc] init];
}
return _operandStack;
}
- (void)pushOperand:(double)operand
{
NSNumber *operandObject = [NSNumber numberWithDouble:operand];
[self.operandStack addObject:operandObject];
}
- (double)popOperand
{
NSNumber *operandObject = [self.operandStack lastObject];
if (operandObject) [self.operandStack removeLastObject];
return [operandObject doubleValue];
}
@end
And there's the controller class, CalculatorViewController: .h
#import <UIKit/UIKit.h>
@interface CalculatorViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *display;
@end
.m
#import "CalculatorViewController.h"
#import "CalculatorBrain.h"
@interface CalculatorViewController ()
@property (nonatomic) BOOL userIsInTheMiddleOfEnteringANumber;
@property (nonatomic, strong) CalculatorBrain *brain;
@end
@implementation CalculatorViewController
- (IBAction)digitPressed:(UIButton *)sender {
NSString *digit = [sender currentTitle];
NSString *currentDisplayText = self.display.text;
if (self.userIsInTheMiddleOfEnteringANumber) {
self.display.text = [currentDisplayText stringByAppendingString:digit];
}
else {
self.display.text = digit;
self.userIsInTheMiddleOfEnteringANumber = YES;
}
}
- (IBAction)enterPressed {
[self.brain pushOperand:[self.display.text doubleValue]];
NSLog(@"count: %lu", (unsigned long) [self.brain.operandStack count]);
NSLog(@"index 0: %@", [self.brain.operandStack objectAtIndex:0]);
self.userIsInTheMiddleOfEnteringANumber = NO;
}
@end
The problem is in the enterPressed method. As you can see, I put 2 NSLog lines to see if the numbers are being pushed into the array, but they're not. The two lines return me 0 and null. I know I don't need to use @synthesize anymore(in the CalculatorBrain class) but I've tried with and without it, and the items are not being added anyway.
Can anybody help me?
Thank you.