我正在上斯坦福的 iPhone 应用程序开发讲座,第一个任务是构建一个 RPN 计算器。
我遇到的问题可能很简单,我错过了。
有一个模型类,叫做 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
还有控制器类 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
问题出在 enterPressed 方法中。如您所见,我放了 2 条 NSLog 行来查看是否将数字推入数组,但事实并非如此。这两行返回我 0 和 null。我知道我不再需要使用@synthesize(在 CalculatorBrain 类中),但我已经尝试过使用和不使用它,并且无论如何都没有添加这些项目。
有谁能够帮我?
谢谢你。