这是一个加法计算器的代码,它通过先输入两个操作数再输入运算来进行运算;像“5 enter 2 enter +”会导致“7”。当用户点击一个数字时,adouble
将被发送到pushOperand:
当用户点击添加按钮时,字符串@"+"
将被发送至performOperation:
。我的问题是制作这些副本有什么意义?program
如果runProgram:
它们都是浅拷贝,并且它们的元素最终都指向 , 和 , 的相同元素NSNumber
和NSString
对象?_programStack
program
stack
#import <Foundation/Foundation.h>
@interface CalculatorBrain : NSObject
@property (nonatomic, readonly) id program;
+(double)runProgram:(id)program;
-(double)performOperation:(NSString *)operation;
@end
#import "CalculatorBrain.h"
@interface CalculatorBrain ()
@property (nonatomic, strong) NSMutableArray *programStack;
@end
@implementation CalculatorBrain
@synthesize programStack = _programStack;
-(NSMutableArray *) programStack {
if (!_programStack)
_programStack = [[NSMutableArray alloc] init];
return _programStack;
}
-(void)pushOperand:(double)operand {
[self.programStack addObject: [NSNumber numberWithDouble: operand]];
}
-(double)performOperation:(NSString *)operation {
[self.programStack addObject: operation];
double result = [CalculatorBrain runProgram: self.program];
return result;
}
-(id)program {
return [self.programStack copy];
}
+(double)runProgram:(id)program {
NSMutableArray *stack;
if ([program isKindOfClass: [NSArray class]])
stack = [program mutableCopy];
return [self popOperandOffProgramStack: stack];
}
+(double)popOperandOffProgramStack:(NSMutableArray *)stack {
double result = 0;
id topOfStack = [stack lastObject];
if (topOfStack)
[stack removeLastObject];
if ([topOfStack isMemberOfClass: [NSNumber class]])
result = [topOfStack doubleValue];
if ([topOfStack isKindOfClass: [NSString class]]) {
NSString *operation = topOfStack;
if ([operation isEqualToString: @"+"]) {
result = [self popOperandOffProgramStack: stack] + [self popOperandOffProgramStack: stack];
}
return result;
}
@end