0

I'm learning iOS development through Stanford's iTunesU program. I am stuck on an unexpected problem I am having.

I have added a clear method, but I am getting this error //Use of undeclared identifier 'operandStack'; did you mean '_operandStack'?

I know I can fix the problem by using [self.operandStack ...etc instead of [operandStack

Why do I need self? Isn't it implied? Why do I not need to use self when referencing _operandStack?

#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];

//*************************** //Use of undeclared identifier 'operandStack'; did you mean '_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
4

1 回答 1

4

因为您已经合成了它(注意:在较新的 Objective-C 版本中,合成是自动的):

@synthesize operandStack = _operandStack;

这意味着您生成了 getter 和 setter,并且您通过调用 _operandStack 来访问该属性。如果您想将其称为operantStack,请将其更改为:

@synthesize operandStack;

相反,如果您使用 self.operandStack,则您使用的是属性生成的 getter/setter,而不是合成的。

使用合成和非合成属性是不同的,没有像许多人认为的那样访问属性的“推荐方式”,它们只是具有不同的含义。例如这里:

- (void) setOperandStack:(NSMutableArray *)operandStack
{
    _operandStack = operandStack;
}

您必须使用综合属性,否则您将进入无限循环。合成属性是自动生成的,非合成属性也是自动生成的,但它可以被覆盖,就像你在那种情况下所做的那样,它也可以在外部访问。

于 2013-04-04T14:40:41.967 回答