【发布时间】:2013-06-01 13:05:20
【问题描述】:
我正在参加Stanford's iPhone application development 的讲座,第一个任务是构建一个 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 类中),但我已经尝试过使用和不使用它,并且无论如何都没有添加这些项目。
谁能帮帮我?
谢谢。
【问题讨论】:
-
在该 getter 中懒惰地创建 NSMutableArray 是非常不标准的。最好在初始化程序中创建它,这也有助于完全消除自定义 getter/setter。
标签: iphone ios objective-c