【发布时间】:2013-04-04 14:36:11
【问题描述】:
我正在通过斯坦福大学的 iTunesU 计划学习 iOS 开发。我遇到了一个意想不到的问题。
我添加了一个 clear 方法,但是我收到了这个错误 //使用未声明的标识符'operandStack';你的意思是'_operandStack'吗?
我知道我可以通过使用 [self.operandStack ...etc 而不是 [operandStack
来解决问题为什么我需要自我?不是暗示了吗?为什么我在引用_operandStack时不需要使用self?
#import "CalculatorBrain.h"
@interface CalculatorBrain()
//string because we are the only ones interested
@property (nonatomic, strong) NSMutableArray *operandStack;
@end
@implementation CalculatorBrain
@synthesize operandStack = _operandStack;
- (void) setOperandStack:(NSMutableArray *)operandStack
{
_operandStack = operandStack;
}
- (NSMutableArray *) operandStack
{
if(_operandStack==nil) _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 !=nil)
{
[self.operandStack removeLastObject];
}
return [operandObject doubleValue];
}
- (void) clear
{
//clear everything
[operandStack removeAllObjects];
//***************************强> //使用未声明的标识符'operandStack';你的意思是“_operandStack”吗?
}
- (double) performOperation:(NSString *)operation
{
double result =0;
//calculate result
if ([operation isEqualToString:@"+"]) {
result = [self popOperand] + [self popOperand];
} else if ([operation isEqualToString:@"*"]) {
result = [self popOperand] * [self popOperand];
} else if ([operation isEqualToString:@"π"]) {
[self pushOperand:3.14159];
NSNumber *operandObject = [self.operandStack lastObject];
return [operandObject doubleValue];
}
[self pushOperand:result];
return result;
}
@end
【问题讨论】:
-
在继续之前再次观看课程。他们对此非常清楚,您应该掌握 setter/getter 与实例变量的概念,并熟悉在整个课程中一直使用的惰性实例化。
-
延迟实例化很容易。我非常了解 getter 和 setter 以及实例变量。我的理解是,在引用实例方法或属性时我们需要使用 self,而我们不需要将 self 用于 _operandStack。在我的 C#/.NET 背景中, this 总是引用当前实例,并且可用于访问实例中可访问的任何对象。
标签: ios objective-c