Domanda

I'm working through the Stanford lectures, calculator tutorial. http://www.stanford.edu/class/cs193p/cgi-bin/drupal/downloads-2011-fall

In it he suggests a good technique for creating an instance of a model is to alloc/init in the getter with:

- (NSMutableArray *)operandStack
{
    if(!_operandStack) {
        _operandStack = [[NSMutableArray alloc] init];
    }
    return _operandStack;
}

However, the first time [operandStack] is used is:

 [self.operandStack addObject:operandObject];

Which, I understand, is using the setter.

I can see that it obviously works (it runs) - but I'm at a loss understanding why if no-ones tried to get anything from operandStack yet. Could someone please enlighten me, I've not had any luck with any searches.

È stato utile?

Soluzione

Your misunderstanding seems to stem from the idea that [self.operandStack addObject:operandObject]; is a "setter" operation. To translate that expression to english:"Send the 'addObject' message to the NSMutableArray returned by the method operandStack, passing it the operandObject object."

This seems to be a dot notation confusion. Dot notation simply resolves to basic function calls. So for example the above code excerpt could be written using the familiar square bracket notation. Like so:

[[self operandStack] addObject:operandObject];

This form is still perfectly valid, and even preferred by some. In this form it makes it a bit clearer to see that you are actually calling the "getter" function.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top