Question

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.

Was it helpful?

Solution 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.

OTHER TIPS

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)

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top