Goal C is to use an accessor if it does nothing

In object c, if using getter and direct access to ivar does exactly the same thing, there is no lazy loading code in latching, everything that it does returns ivar, you will still use the accessory or directly access ivar since there is no difference ? Why?

EDIT: I'm talking about inside a class.

+4
source share
3 answers

I decided to always use [self ivar], and not directly ivar, although I use the standard ObjC notation notation, not the dot notation. The only exception is if [self ivar] is a lazy accessory, and I already used it in the method, and I know that it was initialized, and I don’t want to check if this is 10 more times when I use it in the method.

0
source

There is a slight performance advantage that you can use when using ivar directly. However, to avoid confusion, I usually prefix my ivars with _ at the front, and then synthesize the property using @synthesize foo = _foo; which means that I can either do [self foo] or _foo. Then it becomes clear in the code I'm talking about.

However, there is not much advantage, and some may argue that this is premature optimization. What uses a property (or method) will give you the opportunity to subsequently develop your class and change ivar, but at the same time keep the property the same (for example, make it a calculated property). It will also allow subclasses to override your property and still work.

(By the way, there are some more cases where accessing the property syntax can be useful, for example, when writing to ivar. In this case, maintaining the properties for copying | is preserved can be useful for freeing the previous object and getting the correct sequence of save / free calls)

+6
source

Do you speak outside the classroom or inside? If not, then you always use an accessor. First of all, the default visibility for ivars in ObjC is @protected , so unless you explicitly make them @public , you need to use an accessor. In addition, you use an accessor because you never know if you (or anyone else) can subclass your class and change it so much that you need to use an accessor.

If you speak in the class, you do not need to use an accessory, but if you set the values ​​of @property , there is no reason not to use dot notation, even if you synthesize everything. If you use standard ObjC notation, for example [myObject someVariable] , then repeated nested messages may be hard to read and cluttered.

Indeed, an accessor is not as large as a mutator, because mutators often do more than one. Using both getters (outside the class) and setters is good practice.

0
source

All Articles