我正在开发一个可编程计算器,对于我的生活,我无法理解我做错了什么。
以下是代码的相关部分。(代码未完成,所以我知道周围有额外的东西。)
计算器视图控制器.m
#import "CalculatorViewController.h"
#import "CalculatorBrain.h"
@interface CalculatorViewController ()
@property (nonatomic) BOOL userIsEnteringNumber;
@property (nonatomic) BOOL numberIsNegative;
@property (nonatomic,strong) CalculatorBrain *brain;
@property (nonatomic) NSArray *arrayOfDictionaries;
@property (nonatomic) NSDictionary *dictionary;
@end
@implementation CalculatorViewController
@synthesize display = _display;
@synthesize history = _history;
@synthesize userIsEnteringNumber = _userIsEnteringNumber;
@synthesize numberIsNegative;
@synthesize brain = _brain;
@synthesize arrayOfDictionaries;
@synthesize dictionary;
-(CalculatorBrain *)brain
{
if (!_brain) _brain = [[CalculatorBrain alloc] init];
return _brain;
}
/*snip code for some other methods*/
- (IBAction)variablePressed:(UIButton *)sender
{
NSString *var = sender.currentTitle;
NSDictionary *dict = [self.dictionary initWithObjectsAndKeys:[NSNumber numberWithDouble:3],@"x",[NSNumber numberWithDouble:4.1],@"y",[NSNumber numberWithDouble:-6],@"z",[NSNumber numberWithDouble:8.7263],@"foo",nil];
[self.brain convertVariable:var usingDictionary:dict];
self.display.text = [NSString stringWithFormat:@"%@",var];
self.history.text = [self.history.text stringByAppendingString:sender.currentTitle];
[self.brain pushOperand:[dict objectForKey:var] withDictionary:dict];
}
@end
这是 CalculatorBrain.m。
#import "CalculatorBrain.h"
@interface CalculatorBrain ()
@property (nonatomic, strong) NSMutableArray *operandStack;
@end
@implementation CalculatorBrain
@synthesize operandStack = _operandStack;
-(void)pushOperand:(id)operand withDictionary:(NSDictionary *)dictionary
{
NSNumber *operandAsObject;
if (![operand isKindOfClass:[NSString class]])
{
operandAsObject = operand;
}
else
{
operandAsObject = [dictionary objectForKey:operand];
}
[self.operandStack addObject:operandAsObject];
}
-(double)popOperand
{
NSNumber *operandAsObject = [self.operandStack lastObject];
if (operandAsObject) [self.operandStack removeLastObject];
return [operandAsObject doubleValue];
}
-(double)convertVariable:(NSString *)variable usingDictionary:dictionary
{
double convertedNumber = [[dictionary objectForKey:variable] doubleValue];
return convertedNumber;
}
@end
我无法理解的是CalculatorViewController.m
方法- (IBAction)variablePressed:(UIButton *)sender
。此行使程序崩溃:
NSDictionary *dict = [self.dictionary initWithObjectsAndKeys:[list of objects and keys]];
但如果我成功了
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[list of objects and keys]];
然后一切正常。但如果我尝试做
NSDictionary *dict = [[self.dictionary alloc] initWithObjectsAndKeys:[list of objects and keys]];
在我看来这是正确的做法,然后 XCode 不会让我这样做,所以我显然不理解某些东西。
有什么想法吗?