Objective C - Using an accessor if It does nothing different

丶灬走出姿态 提交于 2020-01-12 08:43:14

问题


In objective c, if the using the getter and directly accessing the ivar do exactly the same thing, no lazy loading code in the getter, all it does is returns the ivar, would you still use the accessor or access the ivar directly since there is no difference? Why?

EDIT: I'm talking about inside the class.


回答1:


There is a small performance advantage to be enjoyed by using the ivar directly. However, to avoid confusion, I typically prefix my ivars with _ on the front, and then synthesize a property using @synthesize foo = _foo; which means I can either do [self foo] or _foo. It then becomes clearer in the code which I'm referring to.

However, the advantage isn't much, and some might argue that this is premature optimisation. What using the property (or method) will give you is the ability to evolve your class later and change the ivar but whilst keeping the property the same (e.g. making it a calculated property). It will also allow subclasses to override your property and still work.

(By the way, there are still some cases where referring to property syntax can be helpful, such as when writing to the ivar. In this case, the property support for copy|retain can be helpful in freeing up the previous object and getting the right sequence of retain/release calls)




回答2:


Are you talking about outside of the class, or within? If without, then you always use the accessor. First of all, the default visibility for ivars in ObjC is @protected, so unless you explicitly make them @public, you have to use an accessor. Aside from this, you use the accessor because you never know if you (or someone else) might subclass your class and change it enough that using the accessor is necessary.

If you're talking about within the class, you don't have to use the accessor, but if you set up @property values, there's no reason not to use the dot notation, even if you're synthesizing everything. If you're using standard ObjC notation, such as [myObject someVariable], then repeated nested messages can get hard to read and cluttered.

Really, the accessor isn't as big a deal as the mutator, because mutators often do more than one thing. Using both getters (outside the class) and setters is good practice.




回答3:


I decided to always use the [self ivar], not directly ivar, even though I use standard ObjC bracket notation , not dot notation. Only exception is if [self ivar] is a lazy-loading accessor and I already used it in the method and I know it has been initialised and I don't want to check if it is nil the 10 more times I use it in the method.



来源:https://stackoverflow.com/questions/1292009/objective-c-using-an-accessor-if-it-does-nothing-different

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!