我正在通過斯坦福大學的iTunesU程序學習iOS開發。我遇到了一個意想不到的問題。爲什麼我必須使用自我。以引用自己的對象
我已經添加了一個明確的方法,但我得到這個錯誤 //使用未聲明的標識符'operandStack';你的意思是'_operandStack'?
我知道我可以用[self.operandStack解決問題...等,而不是[operandStack
爲什麼需要自我?這不是暗示嗎?爲什麼在引用_operandStack時不需要使用self?
#進口 「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/getters的概念與實例變量,並讓自己適應整個課程中始終使用的懶惰實例。 – Mario 2013-04-04 19:27:17
懶惰的實例化非常簡單。我非常瞭解getter和setter以及實例變量。我所理解的是,我們需要在引用實例方法或屬性時使用self,並且我們不需要爲_operandStack使用self。在我的C#/ .net背景中,它總是指向當前實例,並可用於訪問實例中可訪問的任何對象。 – user1060500 2013-04-08 15:49:44