Using self->ivar when accessing instance variables directly

后端 未结 4 1222
孤独总比滥情好
孤独总比滥情好 2020-12-30 10:15

I have noticed that most Objective-C coders never use the self->ivar syntax when accessing instance variables directly. Most sample code that I see simply re

4条回答
  •  一生所求
    2020-12-30 10:29

    Short answer: No, you are not a bad programmer because of that :) There is also no good reason for not writing code this way; most programmers are simply lazy or never really have written an exhausting method in their whole life.

    Long answer: Technically when you access a variable without "self->", the compiler will first for a variable of that name in the local scope and if it cannot find one, it will repeat that search with instance variables. If it finds a hit there, it will actually generate code as if "self->..." had been written there. If there was no match for instance variables either, the compiler would try within global scope, BTW.

    Most programmers only read their own code and they know pretty well what is an instance variable and what not. Once you ever had to work with code you have not written yourself, where the method is 4 screen pages long (and I have a bigg screen), you are really thankful when the programmer made it absolutely clear on every variable access: Is that variable a parameter fed to the method call, a local variable of this method, an instance variable of the object or possibly a global variable (only global to all instances of this class or possibly application global). You are thankful, because if there are just a bunch of variables with similar name and with no special naming or access pattern, however all of different type, you pretty quickly lose oversight. And relying on the fact that Xcode syntax highlighting highlights instance variables in a different way than local variables is also stupid, because no programmer is forced to edit code in Xcode to begin with and even if he does, he may have a color scheme where instance variables are the same color as local ones.

    Accessing instance variables via self-> is perfectly fine, but consider also a to maybe use a prefix/suffix, which will also make obvious those are instance variables and also avoid naming conflicts with method parameters or local variables.

提交回复
热议问题