Accessor Methods: Why does the Getter get posted first?


I have noticed this pattern in other areas of Objective-C programming, but this one is such an obvious case I thought I might as well ask.

In the Accessor Methods section on page 43 it talks about the subject of getters and setters, but I find that very unintuitive (I know I have already begun adjusting my frame of mind on the matter) that the getter is listed before the setter.

How is it that you can get something that hasn’t been set yet? It seems that it should setters and getters, in that order. Additionally the code sequence also follows that same reverse logic pattern:

[code]// a getter method

  • (NSString *)itemName
    // Return a point to the object this BNRItem calls its itemName
    return itemName;

// a setter method

  • (void)setItemName:(NSString *)newItemName
    // Change the instance variable to point to another string,
    // this BNRItem will now call this new string its itemName
    itemName = newItemName;

And so my question is this: why are the getters listed before the setters, when in reality a value has to be set before it can be got! Does the compiler parse the code “backwards”

As noted above, I am willing to modify my perspective on such things if I understand that logic behind it. Please help me understand.


P.S. By reading further I may have answered my own question as the setters are declared in the interface (.h) file and then set and returned in the implementation file. If this is correct then shouldn’t the example on page 43 have it as setters and getters?


I’m by no means any type of guru, but I believe I can summarize an answer to your question.

The getter and setter methods that you show do not depend on any type of order. All the methods in the implementation file are simply “messages” that the class will intercept and respond to. In a sense, it’s listening to any messages that is sent to it, and if it sees one it recognizes (i.e. itemName), then it’ll start processing any commands that are listed within the curly brackets.

This language does not process methods in the order listed within the .m file, it only processes command that are contained within the “message” it intercepts.

Therefore, if the setItemName message is sent to that class before the itemName message is sent, then the value contained within itemName is returned to the message sender. If the itemName message is sent to the class before the setItemName message is sent, then a value of nil will be returned to the sender of the message.

I hope that makes sense, and I hope that last statement is correct.